Python subclass methods for calling parent class members

Source: Internet
Author: User

1. Direct Write class name invocation: Parent_class.parent_attribute (self)

1 classAnimal ():2 3 def __init__ (self, name):4Self.name =name5 6 def say_name (self):7 print (self.name)8 9 Ten classDog (Animal): One  A def __init__ (self, name): - animal.__init__ (self, name) -  the def say_name (self): - animal.say_name (self) -  -  +Dog = Dog ('Xiao Hu') -Dog.say_name () # print ' Little Tiger '

Extension: Instance objects and class objects call instance functions.

1 classAnimal ():2 3 def __init__ (self, name):4Self.name =name5 6 def say_name (self):7 print (self.name)8 9Animal = Animal ('Nada')TenAnimal.say_name () # instance Object Call instance function, output'Nada' OneThe Animal.say_name (Animal) # class object invokes an instance function and needs to pass in an object instance as a parameter, outputting'Nada'

2. Using the super (type, obj) method call: Super (Child_class, Child_object). Parent_attribute (ARG) "No need to write self"

1 classAnimal (Object):2 3 def __init__ (self, name):4 Super (Animal, self). __init__ ()5Self.name =name6 7 def say_name (self):8 print (self.name)9 Ten  One classDog (Animal): A  - def __init__ (self, name): - Super (Dog, self). __init__ (name) the  - def say_name (self): - Super (Dog, self). Say_name () -  +  -Dog = Dog ('Xiao Hu') +Dog.say_name () # Output'Xiao Hu'

Python subclass methods for calling parent class members

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.