Python Object-oriented (bottom)

Source: Internet
Author: User

Inherited

Inheritance describes how the properties of a base class are "inherited" to derived classes. A subclass can inherit any property of its base class, whether it is a data property or a method.
The syntax for creating subclasses looks no different from normal (modern) classes, a class name followed by one or more parent classes that need to derive from it:

...]):    ‘optional class documentation string‘    class_suite

Instance

class Parent(object): # define parent class 定义父类 def parentMethod(self): print ‘calling parent method‘class Child(Parent): # define child class 定义子类 def childMethod(self): print ‘calling child method‘
Inheritance and overwrite inheritance

When a subclass other than Java,python inherits the parent class, all methods of the parent class, including the constructor Init(), are inherited.

 class Parent():     def __init__(self):        Print "Init Parent class instance"     def func(self):        Print "Call parent func" class child(Parent):     def __init__(self):        Print "Init child class instance"Child = Child () Child.func ()

Output

Init Child class Instance
Call parent Func

Super keyword

Super is used to solve multiple inheritance problems, it is not a problem to call the parent class directly with the class name when using single inheritance, but if multiple inheritance is used, it involves various problems such as lookup order (MRO), repeated invocation (Diamond inheritance). The syntax is as follows

Super (type[, obj])

Example

class C(B):    method(self, arg):        self).method(arg)

Attention

Super inheritance can only be used in modern classes and will be an error when used in classic classes.
New class: Must have an inherited class, if there is nothing to inherit, then inherit object
Classic class: There is no parent class, and if you call super at this point there will be an error: "Super () Argument 1 must is type, not Classobj"

Instance

 class Parent(object):     def __init__(self):Self.phone =' 123456 'Self.address =' ABCD ' class child(Parent):     def __init__(self):Super (Child, self). __init__ () Self.data = - def main():Child = Child ()Print "Phone is:", Child.phonePrint "Address is:", child.addressPrint "Data is:", Child.dataif__name__ = =' __main__ ': Main ()

Output

is:  123456is:  is:  100
Rewrite

Subclasses you can override methods that override the parent class as long as you redefine a method with the same name as the parent class's method. Subclasses simply rewrite the func (self) of the previous example's parent class.

 class Parent(): def __init__(self):Print "Init Parent class instance" def func(self):Print "Call parent func" class child(Parent): def __init__(self):Print "Init child class instance"Child = Child () Child.func ()

Output

Childclass instanceChild func
Multiple inheritance

Like C + +, Python allows subclasses to inherit multiple base classes. However, multiple inheritance is not generally recommended. The syntax is as follows:

 class Father():     def __init__(self):        Print "Init Father instance" class mother():     def __init__(self):        Print "init mother instance" class child(Father, mother):    Pass
Built-in functions for classes, instances, and other objects issubclass ()

Boolean functions determine that a class is a subclass or descendant class of another class. It has the following syntax:

Issubclass (Sub, SUP)

Isinstance ()

Boolean functions are useful when determining whether an object is an instance of another given class. It has the following syntax:

Isinstance (Obj1, Obj2)

attr () Series functions
    • Hasattr ()
      Its purpose is to determine whether an object has a specific property, generally used to access a property before a check.

    • GetAttr () and SetAttr ()
      The GetAttr () and setattr () functions obtain and assign values to the object's properties accordingly.

    • Delattr ()
      Delete a specific property

Instance

 class child(Parent):     def __init__(self):Self.data = -Child = Child ()Print "has data attr?", Hasattr (Child,' Data ')Print "Delete attr"Delattr (Child,' Data ')Print "has data attr?", Hasattr (Child,' Data ')Print "Set data attr to"SetAttr (Child,' Data ', $)Print "Data attr is:", GetAttr (Child,' Data ')

Output

hasdata attr? Truedelete attrhasdata attr? Falsesetdata attr to 200data attr is:  200
Privatization

Python does not implement a true package like Java, but is privatized with double dashes and dashes.

    • Double Dash
      Prevent external access. If you add a double dash before func, you can prevent access to instances that include subclasses.
    def __func(self):        print"call"
    • Single Dash
      Prevents the properties of the module from being loaded with "from mymodule import *".

Python Object-oriented (bottom)

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.