Multiple inheritance and fetching objects in Python

Source: Internet
Author: User

1. Multiple inheritance in Python

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:

classA (object):def __init__(Self, a):Print 'init A ...'SELF.A=aclassB (A):def __init__(Self, a): Super (B, self).__init__(a)Print 'init B ...'classC (A):def __init__(Self, a): Super (C, self).__init__(a)Print 'init C ...'classD (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 multiple processes forkingmixin and Multithreading threadingmixin two kinds.

To create a tcpserver for a multi-process pattern:

class mytcpserver (TCPServer, forkingmixin)     Pass

To create a udpserver for 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.

2. Python gets multiple objects

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:

classPerson (object):def __init__(self, Name, gender): Self.name=name Self.gender=GenderclassStudent (person):def __init__(self, name, gender, score): Super (Student, self).__init__(name, gender) Self.score=scoredefWhoAmI (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)'int'>>>> s = Student ('Bob ' ' Male ', ()>>> 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:

>>> GetAttr (s),'name')#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): File"<stdin>", Line 1,inch<module>Attributeerror:'Student'object has no attribute' Age'>>> GetAttr (s),' Age', 20)#Gets the Age property, and returns the default value if the property does not exist:20

Instance:

class Person (object):

def __init__ (self, name, gender, **kw):
Self.name = Name
Self.gender = Gender
Self.__dict__.update (kw)

p = person (' Bob ', ' Male ', age=18, course= ' Python ')
Print (P.age)
Print (P.course)

Results:
Python

Multiple inheritance and fetching objects in Python

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.