optional argument to a subclass of a class

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri May 21 03:43:37 EDT 2010


On Thu, 20 May 2010 23:35:01 -0400, Alex Hall wrote:

>> You overrode the __init__method from the superclass.
>
> I know, I thought I had to in order to make all of Craft's attribs
> available to the Battleship. Is that not the case?

No, the opposite in fact.

One of the basic features of objects (at least as implemented by Python, 
and many other languages) is inheritance. That is, a class inherits 
behaviour and state (methods and attributes) from its parent class (or 
classes).

So if you have a class A and a subclass B, B inherits behaviour from A:

>>> class A:
...     def method(self):
...         print("method in A")
...
>>> class B(A):
...     pass
... 
>>> b = B()
>>> b.method()
method in A


But if you override method, then Python doesn't *automatically* call the 
parent's method. How can it know where to call it, and what to do with 
the result? Should it call it before the new method, or after, or 
somewhere in the middle? It's impossible to tell. 


>>> class C(A):
...     def method(self):
...         print("called from C")
...
>>> c = C()
>>> c.method()
called from C


If you want both behaviours, then you have to explicitly call the parent 
class, and pass the current instance as an argument:

>>> class D(A):
...     def method(self):
...         print("called from D")
...         A.method(self)
...
>>> d = D()
>>> d.method()
called from D
method in A



Exactly the same rules apply to __init__, with the added complication 
that frequently you want to modify the function signature:


>>> class Sandwich:
...     def __init__(self, filling, bread='white'):
...         self.filling = filling
...         self.bread = bread
...     def __str__(self):
...         return ("%s on two slices of %s bread" % 
...         (self.filling, self.bread))
...
>>> s = Sandwich("cheese", "rye")
>>> print(s)
cheese on two slices of rye bread
>>>
>>> class BLT(Sandwich):
...     def __init__(self):
...         Sandwich.__init__(self, "bacon, lettuce and tomato", 
...         "sour dough")
...
>>> b = BLT()
>>> print(b)
bacon, lettuce and tomato on two slices of sour dough bread



Hope this helps.


-- 
Steven



More information about the Python-list mailing list