Python object-oriented programming-encapsulation, inheritance (python3.5)

Source: Internet
Author: User

object-oriented programming three elements: encapsulation, inheritance, and polymorphism. This paper mainly looks at the concepts related to encapsulation and inheritance, and the concept of polymorphism in Python is rather vague, this article does not discuss.

1 package

Encapsulation : The data and operations are assembled together, exposing only a few interfaces for external or subclass access, hiding data and the implementation details of the operation.

In other object-oriented languages, such as Java, property access control generally has three states: private, PROTECTD, public. Nothing in Python is completely invisible, and there is no mechanism for forcing the data to be hidden. So there is no real property in Python that can only be accessed inside the object.
A convention that is adhered to by most Python programmers: A variable that begins with an underscore should be treated as a non-public attribute, i.e. it should be treated as an implementation detail, and its modifications should be undetected.

1.1 Name Management

There is a mechanism in Python that provides limited support for the privatization of class members, called name Management :
Any identifier that begins with at least two underscores, at most one underscore, such as __spam, is converted to the form _classname__spam , where classname is the current class name. This name management mechanism does not consider which namespace the identifier actually belongs to, as long as it occurs in the definition of the class and automatically takes effect.

classChinese:"""A Sample Example Class"""Nationality=' China'    def __init__(self, name, age, gender): Self.name=name self.__age=Age Self.gender=Genderdef __str__(self):return '{} (name={}, age={}, gender={})'. Format (self.__class__, Self.name, self.__age, Self.gender) XM= Chinese ('xiaoming', 18,'male')Print(XM.__dict__)#{' Gender ': ' Male ', ' name ': ' Xiaoming ', ' _chinese__age ':Print(XM)#<class ' __main__. Chinese ' > (name=xiaoming, Age=18, Gender=male)Print(XM.__age)#attributeerror: ' Chinese ' object has no attribute ' __age '
    • __age is automatically converted to _chinese__age in the class and saved in the namespace of the instance;
    • Identifiers in the form of __age that occur inside a class are automatically converted, so the __str__ method can access the __age attribute in this example;
    • Outside of the class (including in subclasses), the __age property cannot be accessed because the attribute does not exist in the instance namespace.
Inherited

inheritance : A reuse mechanism for existing classes. If you make some personalized changes to the existing classes, you can do so by inheriting them instead of modifying the original classes directly.

The inheritance syntax for Python is as follows:

class Derivedclassname (baseclassname):         <statement-1> ...     <statement-N>

Baseclassname represents a class that is inherited, called a base class or parent class.
Derivedclassname is called a subclass. In addition to adding a parent class, the definition and instantiation of subclasses are no different from ordinary classes. You can view its parent class through baseclassname.__bases__ .

    1. subclasses can refer to all properties in the parent class namespace. the lookup order of the property: instance----The parent class----The parent class ...-->object. all classes in Python3 are implicitly inherited from the object class.
    2. Subclasses can override the properties of the parent class. Once the property is overridden, the property that the parent class corresponds to is masked when the property lookup begins before the child class or subclass.
    3. If the subclass is overriding the initialization method, it is best to extend the initialization method of the parent class by invoking the initialization method of the parent class and implementing its own personalization extension.
classAnimal:def __init__(self, Name, age): Self.name=name Self.age= Agedefreply (self):returnSelf.speak ()defSpeak (self):return 'Hello World'classCat (Animal):def __init__(self, name, age, breed): Super ().__init__(name, age) Self.breed=BreeddefSpeak (self):return 'Cat miaow'Print(Cat.__bases__)#(<class ' __main__. Animal ';,)Garfield = Cat ('Garfield', 10,'Garfield')Print(Garfield.reply ())#Cat miaow

Super (). __init__ refers to the initialization method of the ancestor class prior to animal.

Multiple inheritance

Python supports multiple inheritance with the following syntax:

class derivedclassname (Base1, Base2, Base3):         <statement-1> ...     <statement-N>

The main problem to solve for multiple inheritance is the attribute search order:
1. The process of generating a list of classes and their ancestor classes from high to low by search priority is called linearization of the class.
2. Mro:method Resolution Order, which refers to the rules for class linearization, Python3 uses the C3 algorithm. The C3 algorithm guarantees the monotonicity of linearization, which means that if the precedence of C1 is higher than C2 in the linearization of Class C, the C1 precedence is higher than C2 in the linearization of all subclasses of C.
3. You can view the linearization results of a class by derivedclassname.__mro__.

To understand the specific implementation of the C3 algorithm, you can refer to the article: https://www.python.org/download/releases/2.3/mro/

Other

Identifier collisions can occur for data properties and method properties, which can cause unintended property overrides (defined for identifiers), which can cause difficult-to-locate bugs in large projects. To avoid identifier collisions, it is advisable to use some conventions to minimize the probability of collisions. Reference scheme:

    • Capitalize the first letter of the method property, adding a specific prefix to the Data property identifier
    • Using verbs to identify method properties, using nouns to identify data attributes
Reference:

1 file:///Library/Frameworks/Python.framework/Versions/3.5/Resources/English.lproj/Documentation/tutorial/classes.html



Python object-oriented programming-encapsulation, inheritance (python3.5)

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.