Detailed description of object-oriented programming in Python (II)

Source: Internet
Author: User
This article mainly introduces the detailed description of object-oriented programming in Python (below ), this article explains inheritance, super keywords, rewriting, multi-inheritance, classes, built-in functions of instances and other objects, and privatization. For more information, see Inheritance

Inheritance describes how to "inherit" the attributes of the base class to the derived class. A subclass can inherit any attribute of its base class, whether it is a data attribute or a method.
The syntax for creating a subclass seems to be no different from that for a common (new) class. a class name is followed by one or more parent classes that need to be derived from it:

The code is as follows:


Class SubClassName (ParentClass1 [, ParentClass2,...]):
'Optional class documentation string'
Class_suite


Instance

The code is as follows:


Class Parent (object): # define parent class defines the Parent class
Def parentMethod (self ):
Print 'calling parent method'

Class Child (Parent): # define child class defines Child classes
Def childMethod (self ):
Print 'calling child method'


Inheritance and coverage

Inheritance

Different from Java, after the subclass of python inherits the parent class, it inherits all the methods of the parent class, including the constructor init.

The code is 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

The code is as follows:


Init Child class instance
Call parent func


Super keyword

Super is used to solve the problem of multi-inheritance. it is okay to directly call the parent class method using the class name when using single inheritance. However, if multiple inheritance is used, the search order (MRO) is involved) and repeated calls (diamond inheritance. Syntax:

The code is as follows:


Super (type [, obj])


Example

The code is as follows:


Class C (B ):
Def method (self, arg ):
Super (C, self). method (arg)


Note:

Super inheritance can only be used for new classes. when used for classic classes, an error is reported.
New Class: there must be inherited classes. if there is nothing to inherit, it inherits the object
Classic class: no parent class. if super is called at this time, an error occurs: "super () argument 1 must be type, not classobj 』
Instance

The code is as follows:


Class Parent (object ):
Def _ init _ (self ):
Self. phone = '000000'
Self. address = 'abc'

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

The code is as follows:


Phone is: 123456
Address is: abcd
Data is: 100


Rewrite

If a subclass re-defines a method with the same name as the parent class method, it can overwrite the parent class method. the subclass only needs to overwrite the func (self) of the parent class in the previous example.

The code is 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

The code is as follows:


Init Child class instance
Call Child func


Multi-inheritance

Like C ++, Python allows subclass to inherit multiple base classes. However, it is generally not recommended to use multi-inheritance. The syntax is as follows:

The code 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


Class, instance, and other object built-in functions

Issubclass ()

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

The code is 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:

The code is as follows:


Isinstance (obj1, obj2)


Attr () series functions

● Hasattr ()
It is used to determine whether an object has a specific attribute. it is generally used to perform a check before accessing an attribute.
● Getattr () and setattr ()
● The getattr () and setattr () functions obtain and assign attributes to objects accordingly,

● Delattr ()
Delete a specific attribute

Instance

The code is as follows:


Class Child (Parent ):
Def _ init _ (self ):
Self. data = 100

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 attrto 200"
Setattr (child, 'data', 200)
Print "data attr is:", getattr (child, 'data ')


Output

The code is as follows:


Has data attr? True
Delete attr
Has data attr? False
Set data attr to 200
Data attr is: 200

Private

Python does not implement real encapsulation like Java, but uses double dashes and single dashes for privatization.

● Double dashes
Prevent external access. for example, you can add a double dashes before func to prevent access to instances that include child classes.

The code is as follows:


Def _ func (self ):
Print "call"


● Single dashes
Prevents the module attributes from being loaded using "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.