Object-oriented polymorphism

Posted by nonexistentera on Mon, 29 Jul 2019 10:39:15 +0200

I. Concept

What is polymorphism?

Multiple objects of different classes 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 feature (that multiple different objects can respond to the same method and produce different results).

Benefits: For users, it greatly reduces the difficulty of using (previously written USB interface, mouse, keyboard, belongs to polymorphism)

Achieve polymorphism:

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

"""
//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)


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

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

 

2. Functions in Classes

1. A pair of functions

isinstance (parameter a, parameter b):

Determine whether an object is an instance of a class

Object to be judged in parameter 1

Types to be judged in parameter 2

issubclass (parameter 1, parameter 2):

Determine whether a class is a subclass of another class

Parametric 1 is a subclass

Parametric 2 is the parent class

2. Magic Function

_ 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: Delete objects manually, immediately, or automatically at the end of program execution.

Use scenarios: When your object is in use, open resources that are not interpreters: files, network ports, etc.

#del Use cases

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()

    # One thing can be determined here.,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)

#call Opportunity for implementation
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 fixes the number of attributes that are not fixed.

ps: Such an interpreter will not create a namespace for this object, so _dict_ is gone.

Reducing memory overhead

Additionally, when slots occur in a class, the object of that class will not be able to add new attributes.

  

# slots Use
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 Period
print(p.__dict__)

 

3. Realization of Point Grammar vs [] Valuation

The realization of point grammar:

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

These functions reflect how the python interpreter implements 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.

Principle of [] Valuation:

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

 

4. 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 that are greater than or equal to...

Case studies:

The original custom object can't be compared directly by using greater than or less than. We can customize the operator to implement it, so that the custom object can also support the comparison operation.

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)

 

 

5. Two Functions of Symbol Iterator

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

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)

 

VI. Context Management

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 represents entry context

Exit denotes exit context

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

When the code is executed, 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

Note:

The enter function should return the object itself.

The exit function can have a return value, which is a bool type to indicate whether an exception has been handled and is useful only in the context

True means that exceptions are handled.

False, exception not handled, program will interrupt error reporting

Topics: PHP Python network encoding Attribute