Object oriented self study notes (Python version)

Time:2022-1-23

Python object-oriented self-study notes

Note initial

Based on the unfamiliar C + + object-oriented foundation, in order to consolidate and better learn and understand python, I made this clumsy work.
Course source:College of teaching
This course is recommended because the duration of each episode is in line with today’s fast-paced society. In the tide of entertainment to death, it can compress the fragmented time and contribute to your future, and it is attached with an extremely exquisite thought map – XMIND (introduced in station B, which is inconvenient to be attached because of copyright, but deeply admired)

Chapter 1 – Basic Theory (1-5)

Key points: the difference between process oriented and object-oriented (the example of cooking is very vivid)

Chapter 2 — the practice of object-oriented in python (6-82)

Define a class (6)

Class name:
        pass

How to create an object through a class? (7-8)

  1. Create object from class – ` one = money()
  2. Class definition
  3. Create an object based on the class
  4. Returns the unique identity of the object

Attribute correlation (9-23)

The difference between attributes and variables and the judgment basis?

The mind map is very clear, but I don’t want to repeat it

Object properties

  • increase
    Especially initialization——init
  • Delete
    Del this variable
  • change
  • check
    Pay attention to the error report when the access is not available:
    AttributeError: ‘Person’ object has no attribute ‘sex’
    View all properties of the object?
    dict

Class properties

  • 1. Classes are also objects
  • 2. Increase
    It is divided into categories from the inside and from the outside
  • 3. Check
    First find the attribute from the object itself. If it is found, it ends. If it is not found, find the class corresponding to the object according to the class and find it in this class.
  • 4. Change
    Class properties cannot be modified through objects
  • 5. Delete
    It cannot be deleted through objects. Del statements can only delete immediate attributes
  • 6. Attention
    The addition, deletion and modification of class attributes can only be accessed through classes. When querying, they can be accessed through objects and classes!
  • 7. Supplement

Differences and relations between object attributes and class attributes

  • The two are different:
    1. Different storage locations (one is a class and the other is an object)
# 1.  Define a class
class Person:
	age = 10
    pass

# 2.  Create an object based on the class
p = Person()

2. Different levels of abstraction
Classes are abstract
Objects are materialized
3. Different hosts (take the above as an example)
Class – person
Object – P
4. Supplement:
p.age += 1
Person. What are the printing results of age and p.age respectively?
10
11

Method related (24-33)

1. Method concept – def
2. Classification:
Instance method:

class Person:
	def run(self):
	pass

Objects are generally used to call
Class call: an object must be passed because the instance method requires.
Object Calling: there is no need to pass it manually. The interpreter will pass the calling object itself by default.
Class method:

class Person:
	@classmethod
	def countPerson(cls):

Classes are generally used to call
Class call: you don’t need to pass the first parameter manually, but you will automatically pass the called class itself to the past.
Object call: the class corresponding to the called object will be automatically passed to the past without manually passing the first parameter.
Static method ()

class Person:
	@staticemethod
	def countPerson():

Class call: it can be called directly without considering the first parameter.
Object call: call directly
You can call it directly without considering the first parameter
Division basis, etc.: the data type that the first parameter of the method must receive.
No matter what type of method it is, it is stored in the class; Not in the instance
Differences between functions and methods
Functions are independent individuals, and there is almost no shared data between functions,
Method has a host.

Supplement (34-82)

Class related supplement

1. Metaclass (type): structure diagramObject oriented self study notes (Python version)2. Generate project file / class description and generate HTML (37-38)

Attribute related supplement

Privatization attribute

1. Concept
2. Meaning
3. Attention
4. X public attribute

5、_ Y protected properties
6、__ Z private attribute
The implementation mechanism of private attributes — name mangling__ X is another name, e.g_ Class name__ x
Application scenario:

class Person:

    #Main function: after we create an instance object, we will automatically call this method to initialize the object
    def __init__(self):
        self.__age = 18

    def setAge(self, value):
        if isinstance(value, int) and 0 < value < 200:
            self.__age = value
        else:
            Print ("there is something wrong with the data you entered, please re-enter it")

    def getAge(self):
        return self.__age
p1 = Person()
p2 = Person()
p1.setAge(20)
print(p1.getAge())
p2.setAge(240)
print(p2.getAge())

Output is
20
There is a problem with the data you entered, please re-enter
18

Read only attribute (mainly applied to instance attribute)

Some attributes can only be modified internally according to different scenarios, but for the outside world, they cannot be modified and can only be read
1. Scheme I:
Part of privatization: realized by “double underline before attribute”
Partial disclosure: Optimization – decorator @ property
eg:

class Person(object):
    def __init__(self):
        self.__age = 18

    #The main function is that this method can be used in the way of using attributes
    #Associate some "operation methods of attributes" to an attribute
    @property
    def age(self):
        return self.__age
p1 = Person()
# p1._Person__age = 999
p1.__dict__["_Person__age"] = 999
print(p1.age)
print(p1.__dict__)

Output:
999
{’_Person__age’: 999}

Classic and new
Classic class: no inherited object
New class: inherit object
And: in python2, if a class is defined and does not explicitly inherit from object, then this class is an inherited class. If it explicitly inherits from object, it is a new class.
In Python 3, defining a class will implicitly inherit object, so it is already a new class by default.
It is recommended that both Python 2 and 3 explicitly inherit objects.

Function of property
Associate some “attribute operation methods” to an attribute, that is, the deletion, modification and query of an attribute to different methods.
Interpretation of official documents:

def __init__(self, fget=None, fset=None, fdel=None, doc=None): 
Property attribute.
        
          fget
            function to be used for getting an attribute value
          fset
            function to be used for setting an attribute value
          fdel
            function to be used for del'ing an attribute
          doc
            docstring

Use of property as a function in new classes(use case from video)

class Person(object):
    def __init__(self):
        self.__age = 18


    def get_age(self):
        print("----, get")
        return self.__age

    def set_age(self, value):
        print("----, set")
        self.__age = value
    age = property(get_age, set_age)
p = Person()
print(p.age)

p.age = 90
print(p.age)

print(p.__dict__)

Output:
—-, get
18
—-, set
—-, get
90
{’_Person__age’: 90}
Property as a decorator in the use of new classes(use case from video)
Official documents

class C(object):
        @property
        def x(self):
            "I am the 'x' property."
            return self._x
        @x.setter
        def x(self, value):
            self._x = value
        @x.deleter
        def x(self):
            del self._x
    """

Video use case:

class Person(object):
    def __init__(self):
        self.__age = 18

    @property
    def age(self):
        print("----- get")
        return self.__age

    @age.setter
    def age(self, value):
        print("----- set")
        self.__age = value

p = Person()
print(p.age)

p.age = 10
print(p.age)

Use of property in classic classes (the switched version is python2)
In classic classes, property only associates read methods, not set and delete methods.
Generally not

2. Scheme II:
The key lies in two requirements: (1) it can be read. (2) Cannot write
Therefore, the introduction__setattr__(self, key, value):
There is this step

class Person:
    #This method will be called when we add an attribute to an instance through "instance. Attribute = value", or modify the attribute value
    #Inside this method, you can really store this attribute and the corresponding data in the__ dict__ In the dictionary
    def __setattr__(self, key, value):
        print(key, value)

        # 1.  Determine whether key is the name of the read-only attribute we want to set
        if key == "age" and key in self.__dict__.keys():
            Print ("this property is read-only and cannot set data")
        # 2.  If not, add the name of the read-only attribute to this instance
        else:
            # self.key = value
            self.__dict__[key] = value
p1 = Person()
p1.age = 18
print(p1.age)
print(p1.__dict__)

Key points: from the above example
if key == “age” and key in self.dict.keys():
Explanation: selfdict. keys () — dictionary type
At the beginning, there is no age in the dictionary, and then continue the cycle. Therefore, the first addition is successful. After the dictionary has an age, it is only read.

System built-in special properties

(1) Class properties

__ dict__: Class properties
__ bases__: All the parent classes of the class form tuples
__ doc__ Class
__ name__ Class name
__ module__ Class definition module

(2) Instance properties

__ dict__: Class
__ class__: Class corresponding to the instance

Method related supplement

Privatization method

Add two underscores before the function name, which is the same as attribute privatization, and the name reorganization mechanism is the same.

def __ Method ():
	pass

Note: do not define the method of “class name method name”

Built in special methods (to complete specific functions)

  1. Information formatting operation
    (1)、__str__
    Function: the description string of an object, which is more convenient for users to readuserMore friendly
def __str__(self):
	Return "description

Use case:

class Person:
    def __init__(self, n, a):
        self.name = n
        self.age = a

    def __str__(self):
        Return "this person's name is% s, and this person's age is:% s"% (self. Name, self. Age)

p1 = Person("sz", 18)
print(p1)

p2 = Person("zhangsan", 19)
print(p2)
s = str(p1)
print(s, type(s))

(2)__repr__faceDeveloper

def __repr__(self):
	Return "description

Trigger__ str__ How to:

Direct printing: Print (P1)
STR method: S = str (P1) print (s)

Trigger__ repr__ How to:

s=repr(p1) print(s)
Write out the object name in the interactive mode and press enter
  1. Call operation(__call__
    Make the “object” have the ability to call as a function – that is, the method that turns the function into a class
    example:
class Person:
    def __call__(self, *args, **kwargs):
        print("xxx", args, kwargs)
        pass

p = Person()

p(123, 456, name="sz")

Output:
xxx (123, 456) {‘name’: ‘sz’}(tuple Plus Dictionary)
Application scenario:
“Constant parameter” and “non constant parameter” can be separated

  1. Index operation — you can index an instance object
    (make objects similar to dictionaries)
    example:
class Person:
    def __init__(self):
        self. Cache = {}# initialize a dictionary

    def __setitem__(self, key, value):
        # print("setitem", key, value)
        self. Cache [key] = value# operates on the key in the dictionary

    def __getitem__(self, item):
        # print("getitem", item)
        return self.cache[item]

    def __delitem__(self, key):
        # print("delitem", key)
        del self.cache[key]

p = Person()
P ["name"] = "SZ" # when this line of code is executed, the first method will be called
Print (P ["name"]) # calls the second method
Del p["name"]# calls the third method
print(p.cache)

Output:
sz
{}
Explanation of the above example: the commented version operation will have a consequence – that is, value cannot be passed into SZ and there can be no indexkeyOperation. thereforeA dictionary attribute is required to index an object

  1. Slicing operation

Mainly in Python 3, the slicing operation is uniformly managed by the index operation!

def __setitem__(self, key, value):
def __getitem__(self, item):
def __delitem__(self, key):
  1. Comparison operation
    You can customize the “compare size, equality, and true and false” rules for objects. There are six methods: <, >, =, > =, < =,! =
    1、 Enables objects to be compared like numbers
class Person:
    def __init__(self, age, height):
        self.age = age
        self. Height = height # first initialize
    def __eq__(self, other):
        return self. age == other. Age # specifies the attribute through which equal comparisons are compared,
    def __ne__(self, other):
        return self. age !=  other. Age # specifies the attribute through which equal comparisons are compared,
    def __gt__(self, other):#   >
    pass

	def __ge__(self, other):#   >=
    pass

	def __lt__(self, other):#   <
    # print("lt")
    print(self.age)
    print(other.age)
    return self.age < other.age

	def __le__(self, other):#   <=
    pass
p1 = Person(18, 180)
p2 = Person(19, 183)
print(p1 == p2)

#The comparison method can be defined by exchanging parameters to simplify the code

be careful
If only one method is defined for the comparison operator of reverse operation, but another comparison operation is used, the interpreter will call the method by exchanging parameters.
2、 It can also be completed automatically through the decorator

import functools


@functools.total_ordering
class Person:
    def __lt__(self, other):
        print("lt")
        # pass
        return False

    def __eq__(self, other):
        print("eq")
        pass
  1. Traversal operation
    1、 Create an object and use the for in loop to traverse, which can be divided into:
    realization__getitem__Method, low priority
    example:
class Person:
    def __init__(self):
        self.result = 1

    def __getitem__(self, item):
        self.result += 1
        if self.result >= 6:
            Raise stopiteration ("stop traversal")

        return self.result
    pass

p = Person()

for i in p:
    print(i)

realization__iter__Method, high priority
example:

class Person:
    def __init__(self):
        self.result = 1

    def __iter__(self):
        print("iter")
        self.result = 1
        # return iter([1, 2, 3, 4, 5])
        return self

    def __next__(self):
        self.result += 1
        if self.result >= 6:
            Raise stopiteration ("stop traversal")
        return self.result

p = Person()

 for i in p:
     print(i)

2、 By returning an iterator,__next__method
If an object has__iter__Method, which is an iterative object; If an object has__next__Method, which is an iterator. Iteratable objects contain iterators.
To define an iteratable object, you must implement__iter__method;
To define an iterator, you must implement__iter__and__next__method.
example:

class Person:
    def __init__(self):
        self.age = 1


    def __getitem__(self, item):
        return 1
def __iter__(self):
    self. Age = 1 # makes the iterator reusable
    return self

def __next__(self):
    self.age += 1
    if self.age >= 6:
        raise StopIteration("stop")

    return self.age

next()
p = Person()

for i in p:
    print(i)

Import collections # import collection modules
print(isinstance(p, collections.Iterator))
#True is an iterator, that is, the output bool value determines whether the instance is an iterator
Print (isinstance (P, collections. Iteratable)) # determines whether it is an iteratable object
  1. Descriptor
    1、 Concept: YesAn object that describes a property operation——That is, there is a property in the class, which points to a special object, as long as the object can implement three special instance methods(__set____get____delete__)This object is a descriptor.
    2、 Function: it can manage the read, write and delete operations of a class attribute, and verify and filter the data in relevant methods.
    3、 Implementation:
    Method 1: use property:
    example:
class Person:
    def __init__(self):
        self.__age = 10

    @property
    def age(self):
        return self.__age

    @age.setter
    def age(self, value):
        if value < 0:
            value = 0
        self.__age = value

    @age.deleter
    def age(self):
        print("del age")
        del self.__age
P = person() # satisfies the instance of three special properties of the object
p.age = 19
del p.age

Output:del age
Mode 2: use three methods to directly define

class Age:
    def __get__(self, instance, owner):
        print("get")

    def __set__(self, instance, value):
        print("set")

    def __delete__(self, instance):
        print("delete")

class Person:
    age = Age()
p = Person()
p.age = 10
print(p.age)
del p.age

4、 Call details:
1. When called with an instance: up to three methods will be called.
2. When calling with class: only get method will be called at most.
3. Descriptors only work in new classes.
4. Method intercept:__getattribute__With this validation, you can only implement the get method.(I don’t quite understand it here. I’ll leave it to follow)
Data descriptor get set
If the non data descriptor only implements the get method, it is a non data descriptor
Data descriptors > instance Properties > non data descriptors

5、 Data storage problems by descriptor:
First introduce the instance:

class Age(object):
    def __get__(self, instance, owner):
        print("get")
        return instance.v

    def __set__(self, instance, value):
        print("set", self, instance, value)
        instance.v = value

    def __delete__(self, instance):
        print("delete")
        del instance.v


class Person(object):
    age = Age()


p = Person()
p.age = 10
p2 = Person()
p2.age = 11

Output results:
set <main.Age object at 0x000001CDBA867FD0> <main.Person object at 0x000001CDBA867FA0> 10
set <main.Age object at 0x000001CDBA867FD0> <main.Person object at 0x000001CDBA867DC0> 11
It is found that the class attribute age is common to multiple instance objects, so the set method operates on instance.

 instance.v = value
  1. Decorator
    Use classes as decorators. That is, the closure function is used.
    example:
class check:
    def __init__(self, func):
        self.f = func

    def __call__(self, *args, **kwargs):
        Print ("login verification")
        self.f()
@check
def fashuoshuo():
    Print ("send a message")
# fashuoshuo = check(fashuoshuo)

fashuoshuo()

Chapter 3 – life cycle of Python objects and cycle methods (83-94)

Life cycle of listening object

Concept of life cycle

Chapter 4 – object oriented programming – comprehensive case (96-109)

Chapter 5 – three characteristics of object orientation (110-151)

encapsulation

concept

Encapsulate some properties and related methods in an object.
Among them, the internal specific implementation details are hidden from the outside, and the outside world only needs to use them according to the “internally provided interface”.

benefit

  1. It is more convenient to use.
    Because many related functions have been encapsulated into a whole.
    It is similar to providing a toolbox to the outside world
    For different scenarios, you can use different toolboxes

  2. Ensure data security.
    For data with high security level, it can be set to “private”.
    You can control that the data is read-only and cannot be modified by the outside world.
    You can also intercept data write operations and perform data verification and filtering.

  3. It is conducive to code maintenance.
    If the function code needs to be maintained later, you can directly modify the internal code of this class;
    As long as the interface name remains unchanged; The outside world does not need to make any code changes.

inherit

concept

One of the ways in which a class “owns” the “resources” of another class,
Among them, “ownership” refers to the right to use resources rather than the duplication of resources into double resources.
“Resource” – refers to “non private” attributes and methods.
Purpose:Facilitate resource reuse.

classification

Single inheritance

Only one parent class is inherited.

class Dog(Animal):
	pass

Multiple inheritance

Inherited multiple parent classes

class child(Father, Mather):
	pass

Distinguish between type and object

objiectIt is also a class. There are many methods in the official documents. Therefore, defining a class in PY3 will automatically be a new class, that is, inheritanceobjictMethods. Object is the top of the parent-child relationship. It is the parent of all data types.
type——Metaclass,objectAlso bytypeInherited——objectyestypeAn example of. Type is the top of the type instance relationship, and all objects are instances of it.

class Animal:
	pass
class XXX:
	pass
class Dog(Animal,XXX):
	pass

The following flow chart is drawn from this example:
Object oriented self study notes (Python version)

Influence under inheritance

Inheritance of resources

Except for private properties and private methods, other basic properties can be inherited.

Use of resources

  1. Several forms of inheritance:
    (1) Single inheritance chain
    (2) Multiple inheritance chains without overlap
    (3) Overlapping multiple inheritance chains
    Object oriented self study notes (Python version)

  2. Standard order of resource inheritance——Follow the monotony principle
    It can be seen from the above figure
    For single inheritance chain: a-b-c

class C:
    # age = "c"
    pass

class B(C):
    # age = "b"
    pass

class A(B):
    # age = "a"
    pass

# A -> B -> C
print A.age

For multiple inheritance chains without duplication: a-b-d-c-e

class E:
    age = "e"

class D:
    # age = "d"
    pass

class C(E):
    # age = "c"
    pass

class B(D):
    # age = "b"
    pass

class A(B, C):
    # age = "a"
    pass

print A.age

A -> B -> D -> C -> E

For multiple inheritance chains with duplicates: a-b-c-d

class D:
    # age = "d"
    pass

class C(D):
    age = "c"
    pass

class B(D):
    # age = "b"
    pass

class A(B, C):
    # age = "a"
    pass

print A.age
A -> B -> D -> C

  1. Evolution of resource use scheme * (unknown, later)*
    Object oriented self study notes (Python version)
    Object oriented self study notes (Python version)
    Object oriented self study notes (Python version)
    Object oriented self study notes (Python version)
    Object oriented self study notes (Python version)
    Object oriented self study notes (Python version)

Coverage of resources

Accumulation of resources

polymorphic

Concept of polymorphism

A class, extended by a variety of forms, on the premise of inheritance; Different subclasses are used to call the same method of the parent class to produce different functions and various forms when calling.

The embodiment of polymorphism in Python

example:

import abc
class Animal(object, metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def jiao(self):
        pass

    @abc.abstractclassmethod
    def test(cls):
        pass

class Dog(Animal):
    def jiao(self):
        Print ("woof, woof, woof")

    @classmethod
    def test(cls):
        print("xxxxx")
    pass

class Cat(Animal):
    def jiao(self):
        Print ("meow meow")


def test(obj):
    obj.jiao()

d = Dog()
d.jiao()
d.test()