The inheritance of the Python Advanced (iv) class

Source: Internet
Author: User
Tags instance method

Inherit a class

If you have defined the person class and need to define the new Student and Teacher classes, you can inherit directly from the person class:

class Person (object):    def __init__ (self, Name, gender):        self.name = name        Self.gender = Gender

When defining the Student class, you only need to add additional attributes, such as score:

Class Student:    def __init__ (self, name, gender, score):        Super (Student, Self). __INIT__ (name, gender)        Self.score = score  

Be sure to use super (Student, self). __INIT__ (name, gender) to initialize the parent class, otherwise the Student inherited from person will not name< /c4> and gender.

The function super (Student, self) returns the parent class that inherits from the current class, that is, person, and then calls the __init__ () method, noting that the from parameter has passed in super (). It is implicitly passed in __init__ () and does not need to be written (or written).

Task

Refer to the Student class, write a Teacher class, and inherit from person.

Judging type

The function isinstance () can determine the type of a variable that can be used in Python's built-in data types such as str, list, dict, or in our custom classes, which are essentially data types.

Assume that the definition and inheritance of the following person , Student , and Teacher are as follows:

class Person (object): Def __init__ (self, Name, gender): Self.name = Name Self.gender = Genderclass Student (person  Def __init__ (self, name, gender, score):  super (Student, self). __INIT__ (Name, gender)  Self.score = score  class Teacher (   person         super (Teacher, self). __INIT__ (name, gender)  Self.cour SE = course  p = person (' Tim ', ' Male ') s = Student (' Bob ', ' Male ', n) t = Teacher (' Alice ', ' Female ', ' 中文版 ')      

When we get the variable p, s, T , we can use isinstance to determine the type:

>>> isinstance (p, person) True    # p is the person type >>> isinstance (P, Student)False    # p is not student type >>> isinstance (P, Teacher)False   # p is not a Teacher type 

This means that on the inheritance chain, an instance of a parent class cannot be a subclass type, because the child analogy parent has more properties and methods.

We re-examine s:

>>> Isinstance (S, person) True    # s is the person type >>> isinstance (S, Student)true    # s is student type >>> isinstance (S, Teacher) False   # s is not a teacher type  

s is student type, not teacher type, which is easy to understand. However,s is also the person type, because student inherits from person, although it has a few more properties and methods than the person, but the s It is also possible to consider an instance of person.

This means that on an inheritance chain, an instance can be regarded as its own type, or as the type of its parent class.

Task

Depending on the type of inheritance chain, consider whether T is a person,student,teacher,object type and use isinstance () Judgment to verify your answer.

Polymorphic

Class has an inheritance relationship, and the subclass type can be transformed upward as a parent class type, if we derive Student and Teacher from person, and both write a WhoAmI () Method:

class Person (object): Def __init__ (self, Name, gender): Self.name = Name Self.gender = Gender def whoami  Whoami": Return ' I am a Student, my name is%s '% Self.nameclass Teacher (person): Def __init__ (self, name, Gend Er, course): Super (Teacher, self). __INIT__ (name, gender) Self.course = Course def   Whoami    

In a function, if we receive a variable x, the result can be printed correctly whether the x is a person , a Student , or a Teacher:

def who_am_i (x):    print X.whoami ()






Who_am_i (t)

Operation Result:

I am a person, my name is TimI am a Student, my name is Bobi am a Teacher, my name is Alice

This behavior is known as polymorphism. In other words, the method invocation will work on the actual type of x . s is the Student type, which actually has its own WhoAmI () method and the WhoAmI method inherited from person, but calls S.whoami () Always look for its own definition first, and if not, look up the inheritance chain until it is found in a parent class.

Because Python is a dynamic language, the parameter x passed to the function who_am_i (x) is not necessarily a subtype of person or person. An instance of any data type can, as long as it has a whoami () method:

Class Book (object):    def WhoAmI (self):        return ' I am a book '

This is one of the biggest differences between dynamic and static languages, such as Java. A dynamic language invokes an instance method, does not check the type, and can be called as long as the method exists and the parameter is correct.

Task

Python provides an open () function that opens a disk file and returns a file object. The file object has a read () method to read the contents of the files:

For example, read the contents from a file and parse it into JSON results:

Import jsonf = open ('/path/to/file.json ', ' R ') print Json.load (f)

Due to the dynamic nature of Python,json.load () does not necessarily read content from a File object. Any object, as long as the read () method is called a file-like object, can be passed to json.load ().

Please try to write a File-like objectthat wraps a string R ' ["Tim", "Bob", "Alice"] ' into file-like object and by Json.load () parsing.

#-*-Coding:utf-8-*-
class Person (object):
def __init__ (self, Name, gender):
Self.name = Name
Self.gender = Gender
def WhoAmI (self):
Return ' I am a person, my name is%s '% Self.name

Class Student (person):
def __init__ (self, name, gender, score):
Super (Student, self). __INIT__ (name, gender)
Self.score = Score
def WhoAmI (self):
Return ' I am a Student, my name is%s '% Self.name

Class Teacher (person):
def __init__ (self, name, gender, course):
Super (Teacher, self). __INIT__ (name, gender)
Self.course = Course
def WhoAmI (self):
Return ' I am a Teacher, my name is%s '% Self.name


p = person (' Tim ', ' Male ')
s = Student (' Bob ', ' Male ', 88)
t = Teacher (' Alice ', ' Female ', ' 中文版 ')

Print P.whoami ()
Print S.whoami ()
Print T.whoami ()

Run the output result:

I am a person, my name is Tim
I am a Student, my name is Bob
I am a Teacher, my name is Alice

Multiple inheritance

In addition to inheriting from a parent class, Python allows inheritance from multiple parent classes, called multiple inheritance.

The inheritance chain of multiple inheritance is not a tree, it looks like this:

Class A (object):    def __init__ (Self, a):        print ' init a ... '        self.a = AClass B (A):    def __init__ ( Self, a):        super (B, self). __init__ (a)        print ' init B ... ' class C (a):    def __init__ (Self, a):        Super (C, self). __init__ (a)        print ' init C ... ' class D (B, C):    def __init__ (Self, a):        Super (D, self). __init__ (a)        print ' init D ... '   

See:

Like this,D also inherits from B and c, i.e. D has all the functions of A, B, and C . When multiple inheritance calls the __init__ () method through super () ,a is inherited two times, but __init__ () is called only once:

>>> d = d (' d ') init a...init c...init b...init D ...

The purpose of multiple inheritance is to select and inherit subclasses from the two inheritance trees, so that the composition function is used.

For example, Python's Web server has tcpserver, Udpserver, Unixstreamserver, Unixdatagramserver, and the server run mode has Multi-process Forkingmixin and multithreading threadingmixin two kinds.

To create a tcpserverfor a multi-process pattern:

Class Mytcpserver (TCPServer, forkingmixin)    Pass

To create a udpserverfor multithreaded mode:

Class Myudpserver (Udpserver, threadingmixin):    Pass

If there is no multiple inheritance, the 4x2=8 subclasses are required to implement all the possible combinations above.

Task

+-person
+-Student
+-Teacher

is a kind of inheritance tree;

+-Skillmixin
+-Basketballmixin
+-Footballmixin

is a class of inheritance trees.

With multiple inheritance, define "students who can play basketball" and "teachers who can play football."

Get object Information

To get a variable, in addition to using isinstance () to determine whether it is a certain type of instance, there is no other way to obtain more information?

For example, there are already definitions:

class Person (object):    def __init__ (self, Name, gender):        self.name = name        Self.gender = Genderclass Student ( person):    def __init__ (self, name, gender, score):        super (Student, self). __INIT__ (name, gender)        Self.score = Score    def whoAmI (self):        return ' I am a Student, my name is%s '% self.name 

You can first get the type of the variable with the type () function , which returns a type object:

>>> type (123) <type ' int ' >>>> s = Student (' Bob ', ' Male ', A.) >>> type (s) <class ' __ main__. Student ' >

Second, you can use the dir () function to get all the properties of a variable:

>>> dir (123)   # integers also have many properties ... [' __abs__ ', ' __add__ ', ' __and__ ', ' __class__ ', ' __cmp__ ', ...] >>> dir (s) [' __class__ ', ' __delattr__ ', ' __dict__ ', ' __doc__ ', ' __format__ ', ' __getattribute__ ', ' __hash__ ', ' __init__ ', ' __module__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' __weakref__ ', ' gender ', ' name ', ' score ', ' WhoAmI '] 

For instance variables,dir () returns all instance properties, including those with a special meaning such as '__class__'. Notice that the method 'WhoAmI' is also an attribute of s .

How do you get rid of special properties such as ' __xxx__ ' , preserving only our own defined properties? Review the use of the filter () function.

The property returned by dir () is a list of strings, and if a property name is known, the getattr () and setattr () functions are required to get or set the properties of the object:

# Get the Name property ' Bob '>>> setattr (S, ' name ', ' Adam ')  # Set the new Name property >>> s.name ' Adam ' >>> getattr (S, ' age ')  # Gets the Age property, but the attribute does not exist, error:Traceback (most recent call last):  File " <stdin> ", line 1, in <module>attributeerror: ' Student ' object with no attribute ' age '>>> get attr (S, ' age ', a)  # Gets the Age property, and returns the default value if the property does not exist:  
Task

For the definition of the person class:

class Person (object):    def __init__ (self, Name, gender):        self.name = name        Self.gender = Gender

Hopefully, in addition to name and gender, you can provide any additional keyword arguments and bind to the instance, modifying the __init__ () definition of person to complete the function.

Incoming **kw can pass in any number of parameters and bind properties through setattr () .

The inheritance of the Python Advanced (iv) class

Related Article

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.