An explanation of object-oriented programming in Python (bottom)

Source: Internet
Author: User
Inheritance

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:
Copy the Code code as follows:


Class Subclassname (parentclass1[, ParentClass2, ...]):
' Optional class documentation string '
Class_suite


Instance
Copy CodeThe code is as follows:


Class Parent (object): # define parent class definition
def parentmethod (self):
print ' Calling parent method '

Class Child (Parent): # define children class definition subclass
def childmethod (self):
print ' calling child method '


inheritance and Overrides

Inherited

When a subclass other than Java,python inherits the parent class, all methods of the parent class, including the constructor init (), are inherited.
Copy the Code code as follows:


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
Copy CodeThe code is as follows:


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
Copy the Code code as follows:


Super (type[, obj])


Example
Copy CodeThe code is as follows:


Class C (B):
Def method (self, arg):
Super (C, 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
Copy the Code code as follows:


Class Parent (object):
def __init__ (self):
Self.phone = ' 123456 '
self.address = ' ABCD '

Class Child (Parent):
def __init__ (self):
Super (Child, self). __init__ ()
Self.data = 100

def main ():
Child = Child ()
Print "Phone is:", Child.phone
Print "Address is:", child.address
Print "Data is:", Child.data

if __name__ = = ' __main__ ':
Main ()


Output
Copy CodeThe code is as follows:


Phone is:123456
Address IS:ABCD
Data 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.
Copy the Code code as follows:


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
Copy CodeThe code is as follows:


Init Child class Instance
Call Child 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:
Copy the Code code 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:
Copy the Code code as follows:


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:
Copy the Code code as follows:


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
Copy the Code code as follows:


Class Child (Parent):
def __init__ (self):
Self.data = 100

Child = Child ()
Print "Have data attr?", hasattr (Child, ' data ')

print "Delete attr"
Delattr (Child, ' data ')

Print "Have data attr?", hasattr (Child, ' data ')

Print "Set data attr to 200"
SetAttr (Child, ' data ', 200)
Print "Data attr is:", getattr (Child, ' data ')


Output
Copy CodeThe code is as follows:


Has data attr? True
Delete attr
Has data attr? False
Set data attr to 200
Data 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.
Copy the Code code as follows:


def __func (self):
Print "Call"


Single Dash
Prevents the properties of the module from being loaded with "from mymodule import *".
  • 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.