Python-object-oriented (2 Inheritance)

Source: Internet
Author: User

The inheritance base class is defined as follows: class people:
# Define attribute
Name =''
Age = 0
# Define private attribute
_ Weight = 0
Def _ init _ (self, n = "hello", a = 24, w = 45.9 ):
Self. name = n
Self. age =
Self. _ weight = w
Def _ del _ (self ):
Print ("people deconstructor ........")
Def _ repr _ (self ):
Print ("people class ")
Def speak (self ):
Print ("% s is speaking: I am % d years old" % (self. name, self. age ))
Def weight (self ):
Print ("Weight number: % d" % (self. _ weight ))

Class student (people ):
Grade =''
Def _ init _ (self, n, a, w, g ):
People. _ init _ (self, n, a, w)
Self. grade = g


Def speak (self ):
Print ("% s is speaking: I am % d years old, and I am in grade % d" % (self. name, self. age, self. grade ))

Def _ del _ (self ):
Print ("student deconstructor ......")
S = student ('ken', 20, 60, 3)
S. speak ()



Multi-inheritance class speaker ():
Topic =''
Name =''
Def _ init _ (self, n, t ):
Self. name = n
Self. topic = t
Def speak (self ):
Print ("I am % s, I am a speaker! My topic is % s "% (self. name, self. topic ))
Def _ del _ (self ):
Print ("speaker deconstructor .....")

Class sample (speaker, student ):
A =''
Def _ init _ (self, n, a, w, g, t ):
Student. _ init _ (self, n, a, w, g)
Speaker. _ init _ (self, n, t)

Def _ del _ (self ):
Print ('sample deconstructor ')
# Speaker. _ del __()
# Student. _ del __()
Test = sample ("Tim", 25, 80, 4, "Python ")
Test. speak ()
Note the sequence of the parent class in parentheses. If the parent class has the same method name but is not specified in the subclass, search for python from left to right, that is, if the method is not found in the subclass, you can check from left to right whether the parent class contains the method.

Note: 1. in Python, if both the parent class and subclass have redefined the constructor _ init () __, during subclass instantiation, the constructor of the subclass does not automatically call the constructor of the parent class. It must be displayed in the subclass.

2. If you need to call the method of the parent class in the subclass, you need to call the method in the form of parent class name. method. When calling this method, be sure to pass the self parameter in the past.

For the inheritance relationship, the subclass inherits all the public attributes and methods of the parent class, and can be called in the subclass through the parent class name. For private attributes and methods, child classes do not inherit, so they cannot be accessed through the parent class name in child classes.

Python supports multiple inheritance. For multiple inheritance, such

Class SubClass (SuperClass1, SuperClass2)

In this case, if SubClass does not redefine the constructor, which parent class constructor will it automatically call? Remember that the first parent class is the center. If SubClass re-defines the constructor, You need to display and call the constructor of the parent class. At this time, the constructor of the parent class is determined by yourself. If SubClass does not redefine the constructor, only the constructor of the first parent class is executed. In addition, if SuperClass1 and SuperClass2 have methods of the same name, the method in the first parent class is called when the method is called through the instantiated object of the subclass.



Binary Polymorphism
Polymorphism is a variety of forms. Its status is determined during the runtime, and its type cannot be determined during the compilation phase. This is polymorphism. The polymorphism in Python is a little different from that in Java and C ++. the type of the variable in Python is not specified during definition, it determines the type of the variable at runtime as needed (I think this is also a manifestation of polymorphism), and Python itself is an explanatory language without pre-compilation, therefore, it only determines its status at runtime, so it is also said that Python is a multi-state language.
In Python, polymorphism can be reflected in many places. For example, the built-in function len (object) can not only calculate the length of a string, you can also calculate the number of data in objects such as lists and tuples. Here, the specific computing process is determined by the parameter type at runtime, which is a manifestation of polymorphism. This is a bit similar to function overload (a compilation unit has multiple functions with the same name but different parameters). It is equivalent to defining a len function for each type. This is a typical polymorphism. Some friends suggested that Python does not support polymorphism, and I totally disagree.

Essentially, polymorphism means that the same operation can be performed on different objects, but they may present results in multiple forms. Len (object) functions reflect this point. In C ++, Java, and C # compiling languages, the compilation process is divided into Runtime polymorphism and compilation polymorphism. Runtime polymorphism means that a parent class pointer or name is allowed to reference a subclass object or an object method, and the actually called method is the class type method of the object. This is called dynamic binding. During compilation, polymorphism includes template or model, method overload, and method override. Python is a dynamic language, and the dynamic identification of type information reflects the characteristics of polymorphism. In Python, polymorphism is used when you do not know the object type, but need to do something about it.

Two sample codes that can directly describe polymorphism are as follows:
1. Method Polymorphism
[Python] view plaincopy
  1. #-*-Coding: UTF-8 -*-
  2. _ Metaclass _ = type # confirm to use the new class
  3. ClassCalculator:
  4. DefCount (self, args ):
  5. Return1
  6. Calc = calculator () # custom type
  7. FromRandomImportChoice
  8. Obj = choice (['hello, world', [1, 2, 3], calc]) # obj is a random return type.
  9. PrintType (obj)
  10. PrintObj. count ('A') # method Polymorphism

For a temporary object obj, it is obtained by using the Python random function. You can call the count method for calculation if you do not know the specific type (string, tuples, or custom type, we don't care about who (which type) does count implement it.

There is something called "duck type (duck typing)", also speaking of polymorphism:

[Python] view plaincopy
  1. _ Metaclass _ = type # confirm to use the new class
  2. ClassDuck:
  3. DefQuack (self ):
  4. Print"Quaaaaaack! "
  5. DefFeathers (self ):
  6. Print"The duck has white and gray feathers ."
  7. ClassPerson:
  8. DefQuack (self ):
  9. Print"The person imitates a duck ."
  10. DefFeathers (self ):
  11. Print"The person takes a feather from the ground and shows it ."
  12. DefIn_the_forest (duck ):
  13. Duck. quack ()
  14. Duck. feathers ()
  15. DefGame ():
  16. Donald = Duck ()
  17. John = Person ()
  18. In_the_forest (donald)
  19. In_the_forest (john)
  20. Game ()
For the in_the_forest function, the parameter object is a duck type, which implements method polymorphism. However, we actually know that the Person type and Duck are completely different from each other in terms of strict abstraction.
2. Operator Polymorphism

[Python] view plaincopy
  1. DefAdd (x, y ):
  2. ReturnX + y
  3. PrintAdd (1, 2) # output 3
  4. PrintAdd ("hello,", "world") # output hello, world
  5. PrintAdd (1, "abc") # throw an exception TypeError: unsupported operand type (s) for +: 'int' and 'str'
In the above example, it is obvious that the addition operator of Python is "polymorphism". Theoretically, the add method we implement supports arbitrary addition objects, however, we do not need to care about the specific types of the two parameters x and y.
Python also supports Operator overloading. The example is as follows:

[Python] view plaincopy
  1. ClassVector:
  2. Def_ Init _ (self, a, B ):
  3. Self. a =
  4. Self. B = B
  5. Def_ Str _ (self ):
  6. Return'Vector (% d, % d) '% (self. a, self. B)
  7. Def_ Add _ (self, other ):
  8. ReturnVector (self. a + other. a, self. B + other. B)
  9. V1 = Vector (2, 10)
  10. V2 = Vector (5,-2)
  11. PrintV1 + v2
Of course, one or two sample codes cannot fundamentally describe polymorphism. It is generally believed that the most valuable and undervalued feature of object-oriented systems is polymorphism. The implementation of polymorphism is related to the virtual function Address binding of the subclass. The effect of polymorphism is actually related to the dynamic binding of the function address during runtime. In C ++, Java, and C #, there are two methods to implement polymorphism: rewrite and overload, in fact, we can analyze the implementation of polymorphism in Python, which can also be understood as rewriting and overloading in disguise. Many built-in functions and operators in Python are polymorphism.

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.