This article introduces the knowledge points related to object-oriented programming (encapsulation, polymorphism), learning together and making progress together
- For a Python column, see: Life is short - I learn python
Article Directory
1. Packaging
Object-oriented features: encapsulation, inheritance, polymorphism
- The meaning of packaging:
- (1) Put the attributes and methods together as a whole, and then process them by instantiating the object;
- (2) Hiding internal implementation details requires only interaction with the object and its attributes and methods;
- (3) Add access control to the attributes and methods of classes.
- Private permissions: precede attribute and method names with two underscores u
- (1) Private properties and methods of a class cannot be accessed directly through the object, but they can be accessed within the class;
- (2) Private attributes and methods of classes are neither inherited nor accessible by subclasses;
- (3) Private attributes and methods are often used to deal with the internal affairs of classes, and play a security role by not dealing with objects.
class Master(object): def __init__(self): self.kongfu = "Gufa Pancake Fruit Formula" def make_cake(self): print("[time-honored methods] according to <%s> Make a pancake fruit..." % self.kongfu) class School(object): def __init__(self): self.kongfu = "Modern Pancake Fruit Formula" def make_cake(self): print("[modern] according to <%s> Make a pancake fruit..." % self.kongfu) class Prentice(School, Master): def __init__(self): self.kongfu = "Cat's Pancake Fruit Formula" # Private property, which can be called from within a class through self, but not through an object self.__money = 10000 # Private method, which can be called from within a class through self, but not through an object def __print_info(self): print(self.kongfu) print(self.__money) def make_cake(self): self.__init__() print("[Cat's] according to <%s> Make a pancake fruit..." % self.kongfu) def make_old_cake(self): Master.__init__(self) Master.make_cake(self) def make_new_cake(self): School.__init__(self) School.make_cake(self) class PrenticePrentice(Prentice): pass damao = Prentice() # Object cannot access properties and methods of private rights # print(damao.__money) # damao.__print_info() pp = PrenticePrentice() # Subclasses cannot inherit the properties and methods of the parent's private rights print(pp.__money) pp.__print_info()
Traceback (most recent call last): File "D:/Phython/study/venv/Include/hello.py", line 47, in <module> print(damao.__money) AttributeError: 'Prentice' object has no attribute '__money'
- summary
- There are no keywords in Python like public and private in C++ to distinguish between public and private properties.
- Python is distinguished by the naming of attributes, which, if preceded by two underscores'u', indicates that the attribute and method are private or otherwise public.
- Modify the value of a private property
- There are usually two ways to modify an object's attribute value
- Object Name.Property Name=Data--> Modify Directly
- Object name. Method name () --> Indirect modification
- Private properties cannot be directly accessed, so they cannot be modified in the first way. Generally, the value of a private property is modified in the second way: by defining a public method that can be invoked to access the modifications within the public method.
class Master(object): def __init__(self): self.kongfu = "Gufa Pancake Fruit Formula" def make_cake(self): print("[time-honored methods] according to <%s> Make a pancake fruit..." % self.kongfu) class School(object): def __init__(self): self.kongfu = "Modern Pancake Fruit Formula" def make_cake(self): print("[modern] according to <%s> Make a pancake fruit..." % self.kongfu) class Prentice(School, Master): def __init__(self): self.kongfu = "Cat's Pancake Fruit Formula" # Private property, which can be called from within a class through self, but not through an object self.__money = 10000 # In modern software development, get_xxx() and set_xxx() methods are usually defined to obtain and modify private property values. # Returns the value of a private property def get_money(self): return self.__money # Receive parameters, modify values of private properties def set_money(self, num): self.__money = num def make_cake(self): self.__init__() print("[Cat's] according to <%s> Make a pancake fruit..." % self.kongfu) def make_old_cake(self): Master.__init__(self) Master.make_cake(self) def make_new_cake(self): School.__init__(self) School.make_cake(self) class PrenticePrentice(Prentice): pass damao = Prentice() # Object cannot access properties and methods of private rights # print(damao.__money) # damao.__print_info() # You can modify the value of a private property by accessing the public method set_money() damao.set_money(100) # Private property values can be obtained by accessing the public method get_money() print(damao.get_money())
100
2. Polymorphism
So-called polymorphism: The type at definition is different from the type at run time and becomes polymorphism. The concept of polymorphism is applied to strongly typed languages such as Java and C#, while Python advocates "duck type".
-
Duck type: Although I want a duck, you gave me a bird.But as long as the bird walks like a duck, calls like a duck, and swims like a duck, I think it's a duck.
-
Python polymorphism is the weakening type, which focuses on whether the object parameters have specified properties and methods, and if so, determines the appropriateness, regardless of whether the object type is correct.
-
Python Duck Type
class F1(object): def show(self): print('F1.show') class S1(F1): def show(self): print('S1.show') class S2(F1): def show(self): print('S2.show') # Because in Java or C#When defining a function parameter in, you must specify the type of the parameter # In order for the Func function to execute both the show method of the S1 object and the show method of the S2 object, # So in def Func's parameters, obj's type is the parent of S1 and S2, F1 # # The parameters actually passed in are: S1 object and S2 object def Func(obj): # python is a weak type, that is, obj variables can point to it regardless of what is passed in, so there is no so-called polymorphism (weakening the concept) obj.show() s1_obj = S1() Func(s1_obj) # The Func function passes in the object s1_obj of class S1, executes the show method of S1, and the result is: S1.show s2_obj = S2() Func(s2_obj) # Pass in the Func function the object ss_obj of the S class, execute the show method of the S, result: S2.show
S1.show S2.show
-
Popular understanding: Defining obj is a variable that says the type of F1, but when Func functions are actually called, they are not necessarily passed an instance object of the F1 class, they may be an instance object of their subclasses.
-
This is called polymorphism.
- Polymorphism: Different subclass objects, call the same parent method, produce different results
- 1 Inheritance
- (2) Rewrite
- The cases are as follows
# Polymorphism: A variety of forms of the same thing, with animals divided into humans and pigs (at defined angles* class Animal: def run(self): raise AttributeError('Subclasses must implement this method') class People(Animal): def run(self): print('People are walking') class Pig(Animal): def run(self): print('pig is walking') class Dog(Animal): def run(self): print('dog is running') peo = People() pig = Pig() d = Dog() peo.run() pig.run() d.run()
People are walking pig is walking dog is running
- Benefits of polymorphism
- 1. Increase the flexibility of the program
- The user calls in the same form, such as func(animal), regardless of the object.
- 2. Increased program quota scalability
- A new class is created by inheriting the animal class, so the user does not need to change his code or invoke it with a func(animal)
Class and instance attributes
- Let's start with class and instance properties
- In the previous examples we touched instance properties (object properties), which, as the name implies, are properties owned by class objects, which are common to all instance objects of class objects and have only one copy in memory, a bit like the static member variables of classes in C++.
- For public class attributes, outside the class, they can be accessed through class objects and instance objects
- Class Properties
class People(object): name = 'Tom' # Public Class Properties __age = 12 # Private Class Properties p = People() print(p.name) # Correct print(People.name) # Correct print(p.__age) # Error, private class properties cannot be accessed outside the class through instance objects print(People.__age) # Error, private class properties cannot be accessed outside the class object
- Instance Properties (Object Properties)
class People(object): address = 'Shandong' # Class Properties def __init__(self): self.name = 'xiaowang' # Instance Properties self.age = 20 # Instance Properties p = People() p.age = 12 # Instance Properties print(p.address) # Correct print(p.name) # Correct print(p.age) # Correct print(People.address) # Correct print(People.name) # error print(People.age) # error
Shandong xiaowang 12 //Shandong Traceback (most recent call last): File "D:/Phython/study/venv/Include/hello.py", line 14, in <module> print(People.name) # error AttributeError: type object 'People' has no attribute 'name'
- Modify class properties by instance (object)
class People(object): country = 'china' #Class Properties print(People.country) p = People() print(p.country) p.country = 'japan' print(p.country) # Instance properties block class properties with the same name print(People.country) del p.country # Delete Instance Properties print(p.country)
china china japan china china
- summary
- If you need to modify a class property outside of a class, you must reference it through a class object and then modify it.
- (2) Referencing through an instance object results in an instance property with the same name, which modifies the instance property without affecting the class property, and then if referencing the property with that name through the instance object, the instance property will force the masking of the class property, that is, referencing the instance property unless the instance property is deleted.
4. Static and Class Methods
- Class method
- Is a method owned by a class object and requires a modifier @classmethod to identify it as a class method
- For class methods, the first parameter must be a class object, usually CLS as the first parameter (of course, variables with other names can be used as its first parameter, but most people are accustomed to using'cls'as the first parameter name, it is better to use'cls'), which can be accessed through instance objects and class objects.
class People(object): country = 'china' #Class methods, decorated with classmethod s @classmethod def get_country(cls): return cls.country p = People() print(p.get_country()) #Can be referenced with instance objects print(People.get_country()) #References can be made through class objects
china china
- Another use of class methods is to modify class properties:
class People(object): country = 'china' #Class methods, decorated with classmethod s @classmethod def get_country(cls): return cls.country @classmethod def set_country(cls,country): cls.country = country p = People() print(p.get_country()) #Can be accessed through an instance object print(People.get_country()) #Accessible through classes p.set_country("japan") print(p.get_country()) print(People.get_country())
- Run Results
china china japan japan
- The result shows that after class method modification of class properties, access through both class and instance objects has changed
- Static method
- Modifiers @staticmethod are required to modify them, and static methods do not require multiple parameters and can be accessed through objects and classes.
class People(object): country = 'china' @staticmethod #Static method def get_country(): return People.country p = People() # Accessing static methods through objects print(p.get_country()) # Accessing static methods through classes print(People.get_country())
china china
- summary
- (1) From the definition of class method, instance method and static method, we can see that the first parameter of class method is class object cls, so the properties and methods of class object must be referenced by cls;
- (2) The first parameter of the instance method is the instance object self, so it may be a class attribute or an instance attribute that is referenced by the self (this requires specific analysis), but in the case of class and instance attributes with the same name, the instance attribute takes precedence.
- (3) There is no need to define additional parameters in static methods, so if class attributes are referenced in static methods, they must be referenced through class instance objects.
-
The best investment is in yourself
- Chenling's 48th Blog in 2020.04.05