Python's self-taught music-inheriting new classes and classic classes

Source: Internet
Author: User

#Author: Clark
Class Animal (object): #python3中新式类写法, Inherit object (base class for all classes)
#kind = "" #类属性
def __init__ (Self,name,age,food): #name等是实例属性 The Init method is called the construction method __del__ is the destructor method
Self. Name = Name
Self. Age = Age
Self.food = Food
Def eat (self):
Print ('%s is eat%s '% (self. Name,self.food))
def barking (self):
Print ("%s is barking"%self. Name)

Class Dog (Animal): #狗是动物的子类, if you add a new attribute and want to inherit the properties of the parent class, write as follows
def __init__ (Self,name,age,food,kind):
#Animal. __init__ (Self,name,age,food) Classic class, this kind of writing is cumbersome, if the class inherits the same properties of multiple classes, it is necessary to write each class, the new class use Super style, write a line
Super (Dog,self) __init__ (Name,age,food)
Self.kind = Kind
def barking (self):
Print ("The barking of%s is wangwangwang!" %self. Name)
Class Cat (Animal):
def __init__ (Self,name,age,food,kind):
#Animal. __init__ (Self,name,age,food)
Super (Cat,self) __init__ (Name,age,food)
Self.kind = Kind
def barking (self):
Print ("The barking of%s is Miaomiaomiao"%self. Name)

Dog_teddy = Dog ("Ahuang", 3, "Bone", "Teddy")
Dog_teddy.eat ()
Cat_xiaohua = Cat ("Xiaohua", 2, "Fish", "cat")
Cat_xiaohua.eat ()
Dog_teddy.barking ()
Cat_xiaohua.barking ()

The result of the operation is:

Ahuang is eat bone
Xiaohua is eat fish
The barking of Ahuang is wangwangwang!
The barking of Xiaohua is Miaomiaomiao

Python's self-taught music-inheriting new classes and classic classes

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.