[Tutor] Calling method in parent class
The Green Tea Leaf
thegreentealeaf at gmail.com
Tue May 12 10:55:18 CEST 2009
OK, bad example. But assume I have the same method in both classes and
want to call the method in the parent.
On Tue, May 12, 2009 at 10:26, Jeremiah Dodds <jeremiah.dodds at gmail.com> wrote:
>
>
> On Tue, May 12, 2009 at 9:05 AM, The Green Tea Leaf
> <thegreentealeaf at gmail.com> wrote:
>>
>> Hi,
>> I've started to learn Python and I'm a bit confused over how to call a
>> method in a parent class. Assume I have:
>>
>> class Parent(object):
>> def somemethod( self, bla ):
>> print 'Parent',bla
>>
>> I then create a child class that want to call somemethod. As I
>> understand it I can either do it like this
>>
>> class Child(Parent):
>> def somemethod( self, bla ):
>> Parent.somemethod(self,bla)
>>
>> or like this
>>
>> class Child(Parent):
>> def somemethod( self, bla ):
>> super(Child,self).somemethod(bla)
>>
>> The first version seem to have the obvious disadvantage that I need to
>> know the name of the parent class when I write the call, so I thought
>> that the second version was the "proper" way of doing it. But when
>> doing some research on the web it seem like the second version also
>> have some problems.
>>
>> My question is simple: what is the "best" way of doing this and why?
>> Or should I mix both these approaches?
>>
>> --
>
> Assuming you don't have the same method in Child, just use self.somemethod:
>
>
> In [2]: class Parent(object):
> ...: def foo(self):
> ...: print "in parent foo"
> ...:
>
> In [3]: class Child(Parent):
> ...: pass
> ...:
>
> In [4]: x = Child()
>
> In [5]: x.foo
> Out[5]: <bound method Child.foo of <__main__.Child object at 0x999252c>>
>
> In [6]: x.foo()
> in parent foo
>
> In [7]: class Child(Parent):
> ...: def bar(self):
> ...: self.foo()
> ...: print "in child bar"
> ...:
>
> In [8]: x = Child()
>
> In [9]: x.bar()
> in parent foo
> in child bar
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
--
The Green Tea Leaf thegreentealeaf at gmail.com thegreentealeaf.blogspot.com
More information about the Tutor
mailing list