Polymorphism of Object-Oriented Foundation

polymorphic

Concept:

A thing has many different forms.

For example, water is solid and gaseous.

Bumblebee: Autobots, Cars, Airplanes

Official Interpretation: Multiple different classes of objects can respond to the same method and produce different results

First of all, it is emphasized that polymorphism is not a special grammar, but a state, a characteristic (that multiple different objects can respond to the same method and produce different results).

Many objects have the same usage method.

Benefits:

For users, it greatly reduces the difficulty of use.

The USB interface we wrote before, the mouse and the keyboard are polymorphic.

Achieve polymorphism:

The interface Abstract duck-like type can write polymorphic code, the simplest is the duck type.

Case:

"""
//Manage chickens, ducks and geese
//How can the most convenient management, that is, I say the same sentence, they can understand.
//Both have the same approach

"""
class JI:
    def bark(self):
        print("Brother")

    def spawn(self):
        print("Laying eggs..")

class Duck:
    def bark(self):
        print("Gagaga")

    def spawn(self):
        print("Laying duck eggs")

class E:
    def bark(self):
        print("Hunger and hunger....")

    def spawn(self):
        print("Lay goose eggs..")

j = JI()
y = Duck()
e = E()

def mange(obj):
    obj.spawn()


mange(j)
mange(y)
mange(e)


# There are polymorphisms everywhere in python  
a = 10
b = "10"
c = [10]

print(type(a))
print(type(b))
print(type(c))

isinstance

Determine whether an object is an instance of a class

Object to be judged by parameter 1

Types to be judged by parameter 2

issubclass

Determine whether a class is a subclass of another class

The first parameter is subclass

The second parameter is the parent class.

str

_ str_ converts an object to a string, and the result of the conversion is the return value of the function. 
Scenario: We can use this function to define the object in print format.

del

Execution timing: When the object is deleted manually, it will be executed immediately, or when the program runs, it will be executed automatically. 
Use scenarios: When your object is in use, open resources that are not interpreters: files, network ports, etc. 
        
# del use case

# class FileTool:
#     """"This class is used to simplify the reading and writing of files""""
# 
#     def __init__(self,path):
#         self.file = open(path,"rt",encoding="utf-8")
#         self.a = 100
# 
#     def read(self):
#         return self.file.read()
# 
#     # Here's one thing to be sure, this object is definitely not used, so you can safely close the question file.
#     def __del__(self):
#         self.file.close()
# 
# 
# tool = FileTool("a.txt")
# print(tool.read())

call

Execution timing: Automatically executes when an object is called (both object and parentheses)

Test:

#Timing of call execution
class A:
    def __call__(self, *args, **kwargs):
        print("call run")
        print(args)
        print(kwargs)

a = A()
a(1,a=100)

slots

This property is a class property used to optimize object memory usage
 The principle of optimization has fixed the number of attributes that are not fixed.
Such an interpreter would not create a namespace for this object, so _dict__is gone.  
So as to achieve the effect of reducing memory overhead 

In addition, when slots appear in the class, it will cause the object of this class to be unable to add new attributes.  
# Use of slots
class Person:

    __slots__ = ["name"]
    def __init__(self,name):
        self.name = name

p =  Person("jck")

# View memory usage
# print(sys.getsizeof(p))
# p.age = 20 # Cannot add

# dict is gone
print(p.__dict__)

getattr setattr delattr

getattr accesses attributes with points if attributes do not exist
 When setattr sets properties with points
 delattr executes when deleting attributes with del objects. attributes


These functions reflect how the python interpreter implements point-to-point access to attributes 

getattribute This function is also used to get attributes
 If a getattribute exists, the function is executed first, if no attribute is obtained, the getattr function is continued to be called, and if it is obtained, it is returned directly.  

.

The Real Principle of []

getitem setitem delitem

Any symbol will be interpreted as a special meaning by the interpreter, such as. [] ()

getitem is executed when you use middle brackets to get attributes
 setitem is executed when you use middle brackets to set properties
 Deltem is executed when you delete attributes with middle brackets

Operator overloading

When we use a symbol, the python interpreter defines a meaning for the symbol and calls the corresponding processing function. When we need to customize the object comparison rules, we can cover a series of methods in subclasses, such as greater than or equal.

Case:

The original custom object can't be compared directly by using greater than or less than. We can customize operators to achieve this, so that the custom object also supports comparison operators.

class Student(object):
    def __init__(self,name,height,age):
        self.name = name
        self.height = height
        self.age = age

    def __gt__(self, other):
        # print(self)
        # print(other)
        # print("__gt__")
        return self.height > other.height
    
    def __lt__(self, other):
        return self.height < other.height

    def __eq__(self, other):
        if self.name == other.name and  self.age == other.age and self.height == other.height:
            return True
        return False

stu1 = Student("jack",180,28)
stu2 = Student("jack",180,28)
# print(stu1 < stu2)
print(stu1 == stu2)

In the above code, another refers to another object that participates in the comparison.

Bigger than or less is enough to implement only one, and symbols will automatically exchange the positions of two objects if different interpreters are used.

iterator protocol

Iterator is an object with _iter_ and _next__
We can add these two methods to an object to make it an iterator 

Case:

class MyRange:

    def __init__(self,start,end,step):
        self.start = start
        self.end = end
        self.step = step

    def __iter__(self):
        return self

    def __next__(self):
        a = self.start
        self.start += self.step
        if a < self.end:
            return a
        else:
            raise StopIteration
            
for i in MyRange(1,10,2):
    print(i)
   

Context management

Context context

This concept belongs to Linguistics and refers to the meaning of a paragraph, referring to the current context.

In python, context can be understood as a code interval, a range, such as a file opened with open, that is valid only in this context

Two methods are involved:

enter

Enter the context.

exit

Represents an exit context.

When the with statement is executed, enter is executed first.

When the code executes after execution, or if the code encounters an exception, it executes the exit immediately and passes in an error message.

Contains the type of error. Error information. Error tracking information

Be careful:

The enter function should return the object itself 
The exit function can have a return value, which is a bool type used to indicate whether an exception is handled or not, and is useful only in the context where an exception occurs.
True means that exceptions are handled. 
False, exception not handled, program will interrupt error reporting

Keywords: PHP Python less network encoding

Added by Banacek on Mon, 29 Jul 2019 13:56:32 +0300