1.26 python knowledge advanced-inheritance

Source: Internet
Author: User
Tags class definition

Inherited

Inheritance (inheritance) is the main method of code important in object-oriented programming design. Inheritance is the ability to allow the use of existing classes, and to extend these capabilities without rewriting the original classes. Inheritance avoids issues such as code duplication and related code maintenance.

The inherited class is called the base class, the parent class, or the superclass (super Class), and the new class created through inheritance is called a subclass (subclass) or derived class (Derived).

Declaration format:

Class derived class (base class 1,[base class 2, ...] ):

Class Body

where the derived class name is followed by the name tuple for all base classes. If the base class is not specified in the class definition, the default base class is Objec. object is the root class for all objects.

Inheritance of multiple classes can form hierarchical relationships, through the method of the class MRO () or the properties of the class __mro__ can output its inherited hierarchies. For example:

class Pass class Pass class Pass class Pass class Pass Print (D.mro ()) Print (E.__mro__)
------------------Line----------------------

[<class '__main__. D', <class '__main__. A', <class 'Object'>] (<class '__main__. E', <class '__main__. B', <class '__main__. D', <class '__main__. A', <class 'Object'>)

When declaring a derived class, you must call the constructor of the base class in its constructor. Call Format:

    base class name. __init__ (self, parameter list)

Define a car class, and then define a Electriccar class that inherits the car class properties and methods, the sample code:

classCar (object):def __init__(self, make, model, year): Self.make=Make Self.model=Model Self.year=Year self.odometer_reading=0defGet_descriptive_name (self): Long_name= str (self.year) +' '+ Self.make +' '+Self.modelreturnLong_name.title ()defRead_odometer (self):Print("This car has"+ STR (self.odometer_reading) +"miles on it.")    defUpdate_odometer (self, mileage):ifMileage >=self.odometer_reading:self.odometer_reading=MileageElse:            Print("You can ' t Roll back an odometer!")    defIncrement_odometer (self, Miles): self.odometer_reading+=milesclassElectriccar (Car):def __init__(self, make, model, year): Car.__init__(self, make, model, year) My_tesla= Electriccar ('Tesla','Model S', 2016)Print(My_tesla.get_descriptive_name ())
------------------Line----------------------
Tesla Model S

Here car is Electriccar's "parent" or "superclass", and Electriccar is the "subclass" or "derived class" of car.

The code "car.__init__ (self, made, model, year)" Lets Python make the Electriccar instance contain all the properties of the parent class by calling __init__ () in the Car class.

After you have one class inherit from another, you can add the new properties and methods required by the zone's molecular classes and the parent class to add unique properties (batteries) to the electric vehicle. Example code:

classCar (object):--Snip--classElectriccar (Car):def __init__(self, make, model, year): Car.__init__(self, make, model, year) Self.battery_size= 70defdescribe_battery (self):Print("This car has a"+ STR (self.battery_size) +"-kwh Battery.") My_tesla= Electriccar ('Tesla','Model S', 2016)Print(My_tesla.get_descriptive_name ()) My_tesla.describe_battery ()
------------------Line----------------------
2016Tesla Model sthis car has a70-kwh Battery.

Sometimes some of the methods of the parent class may not have some of the attributes of the subclass, we need to reconstruct the method of the parent class, and we can redefine a method in the subclass that has the same name as the method of the parent class to be overridden. If there is a Fill_gas_tank () method in the car class, we refactor in the Electriccar. Example code:

class Electriccar (Car):     --Snip-    def  Fill_gas_tank (self):        print("thiscar does ' t need a gas tank! ")

Remember, first inherit, then refactor.

  

Python supports multiple inheritance, where a derived class can inherit multiple base classes.

Inheritance of multiple classes can form hierarchical relationships, through the method of the class MRO () or the properties of the class __mro__ can output its inherited hierarchies. For example:

Class A:passclass B (a): Passclass C (b): Passclass D (A): Passclass E (b, D): Passprint(D.mro ()) print (e.__mro__)
------------------Line----------------------

[<class ' __main__. D ';, <class ' __main__. A ';, <class ' object ' >]
(<class ' __main__. E ';, <class ' __main__. B ';, <class ' __main__. D ';, <class ' __main__. A ';, <class ' object ' >)

  Attached 1, Practice code:

classSchoolmember (object): members=0def __init__(self, name, age, Sex): Self.name=name Self.age=Age Self.sex=sex self.enroll ()defEnroll (self):Print("just enrolled a school member [%s]."%self.name) Schoolmember.members+ = 1defTell (self):Print("------%s Info------"%self.name) forKvinchSelf.__dict__. Items ():Print("\ t", K,v)def __del__(self):Print("fired [%s] ..."%self.name) Schoolmember.members+ = 1classTeacher (schoolmember):def __init__(self, name, age, sex, salary, course): Schoolmember.__init__(self, name, age, sex) self.salary=Salary Self.course=CoursedefTeaching (self):Print("Teacher [%s] is teaching [%s]."%(Self.name, self.course))classStudent (schoolmember):def __init__(self, name, age, sex, course, tuition): Schoolmember.__init__(self, name, age, sex) self.course=Course Self.tuition=Tuition Self.amount=0defpay_tuition (Self, amount):Print("Student [%s] has just paied [%s]."%(Self.name, amount)) Self.amount+=amountt1= Teacher ("Alex", 33,"M", 2000,"Python") S1= Student ("John", 20,"M","Python", 30000)

  Attached 2, questions about the old and new categories:

Notation 1, also known as the Classic class:

    base class name. __init__ (Self, property in base class)

Notation 2, also known as the new type of writing:

In Python 2.7:

    Super (subclass name, self). __init__ (attributes in the base class)

In Python 3.x:

    Super (). __init__ (attributes in a base class)

Note: When using inheritance in Python 2.7, be sure to specify object within parentheses when defining the parent class.

  

1.26 python knowledge advanced-inheritance

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.