python polymorphism, combination, reflection

Polymorphism, polymorphism

polymorphic

Polymorphic popular understanding, like diga Altman has three forms, how to change or diga Altman

  • Definition: polymorphism refers to a class of things with multiple forms

Examples are as follows:

'''Animals have many forms of expression, and people are also one of the animals. Speaking here is an animal'''
class Animal():
    def speak(self):
        print('Animal calls--->', end='')


class Cat(Animal):
    def speak(self):
        print('cat ')


class Dog(Animal):
    def speak(self):
        print('Woof, woof')


class People(Animal):
    def speak(self):
        print('Ah, ah')

ani = Animal()

ani.speak()
cat = Cat()
cat.speak()

ani.speak()
dog = Dog()
dog.speak()

ani.speak()
peo = People()
peo.speak()

# result
 Animal calls--->cat 
Animal calls--->Woof, woof
 Animal calls--->Ah, ah

Polymorphism

  • Polymorphism refers to the direct use of objects without considering the specific types of objects. Polymorphism is the characteristics of different implementation methods when the same operation acts on different instances

Take the above example:

# Polymorphism
# Unified interface, normalization operation
def Speack(animal):
    animal.speak()
'''
Because all animals will "say" that it is the same operation, but different parameters are called and different results are output, which is the embodiment of polymorphism
'''

Speack(cat)
Speack(dog)
Speack(peo)

# result 
cat 
Woof, woof
 Ah, ah

Advantages of polymorphism: it increases the scalability of the program, so that each instantiated object is called in the same form. Polymorphism also increases the scalability of the program and reduces the redundancy of the code by inheriting the parent class

class Pig(Animal):
    def speak(self):
        print('Hum')

pig = Pig()
pig.speak()

Duck type


In the above example, as long as it is an animal, you can directly use the same method! In fact, polymorphism also limits the use of subclasses (abstract classes can also restrict subclasses). When defining subclasses, there must be a speak() method to count as animal classes. Therefore, python recommends the use of "duck type", which is not dependent on Inheritance and can also use objects without considering object types.

class People():
    def speak(self):
        print('Ah, ah')

class Pig():
    def speak(self):
        print('Hum')

class Dog():
    def speak(self):
        print('Woof, woof')


def Speak(animal):
    animal.speak()

peo = People()
pig = Pig()
dog = Dog()

Speak(peo)
Speak(pig)
Speak(dog)

# result
 Ah, ah
 Hum
 Woof, woof

A parent class restricts the behavior of its children

  • Abstract class (abc module)
  • inherit

Examples of active error reporting:

'''Parent restricted subclass'''

class Txt():
    # The parent class limits the functions that the child class must implement
    def read(self):
        raise Exception("It's a document read function")



class Conf(Txt):
    pass
    # The read function is not implemented, and the inheritance error is reported

class Bin(Txt):
    def read(self):
        print('Reading method')

# conf = Conf()
# conf.read()  # --->Exception: if it is a file, it must have the read function

bin = Bin()
bin.read()

combination

The problem of code redundancy between classes can be solved by inheritance or super() method. In fact, we can also solve the problem of code redundancy between classes by composition

Combination: the combination of classes in which the objects of another class are used as data attributes. Combination usually represents the "yes" relationship

class People():
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender


class Course():
    def __init__(self, name, period, price):
        self.name = name
        self.period = period
        self.price = price


class Student(Course, People):
    def __init__(self, name, age, gender, course=None):

        if course is None:
            course = []
        self.courses = course
        super().__init__(name, age, gender)

# Instantiate Student object
stu = Student('HammerZe', 18, 'male')

# Instantiate course object
python = Course('python','6m',10000)
linux = Course('linux','5m',10000)

# combination
stu.courses.append(python.name)
stu.courses.append(linux.name)


print(stu.courses)

# ['python', 'linux']

Object oriented built-in functions

  • __ init__ (): initialization method

  • __ str__ (): function triggered automatically when printing objects

  • __ del__ (): triggered automatically when an object is deleted

  • __ call__ (): automatically triggered when objects are bracketed

  • __ enter__ (): the with statement appears, and the object's__ enter__ Triggered, if there is a return value, it is assigned to the variable declared by as

  • __ exit__ (): execute this method when the code block in with is completed

'''__str__() \ __del__() \ __call__()'''
class Foo():
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

    '''Print when outputting objects,The return value can only be a string'''
    def __str__(self):
        return 'Output object return'

    '''Print when deleting objects'''
    # 1. Delete object execution
    # 2. If the object is not deleted, the program will be executed automatically after execution__ del__ ()
    def __del__(self):
        print('Delete object execution')
    
    '''Object is automatically triggered with parentheses'''
    def __call__(self, *args, **kwargs):
        print('Object is automatically triggered with parentheses')


stu = Foo('HammerZe', 18, 'male')
print(stu) # --->Output object return
del stu.name  # --->Delete object execution
stu() # --->Object is automatically triggered with parentheses

'''__enter__(),__exit__()  '''
class Open():
    def __init__(self,name):
        self.name = name

    def __enter__(self):
        print('appear with Statement to trigger this method. If the method has a return value assigned to as Subsequent variables')
        return 123

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('with This method is triggered after the statement is executed')

with Open('a.txt') as f:
    pass
print(f) # --->123

# --->The with statement appears to trigger this method. If the method has a return value assigned to the variable after as
# --->This method is triggered after the with statement is executed

reflex

  • hasattr(obj,pro): press pro to judge whether there is obj Pro attribute
  • getattr(obj,pro,None): press pro to judge whether there is obj Pro attribute, no return None
  • setattr(obj,pro,value): set obj The value of Pro is equivalent to obj pro = value
  • delattr(obj,pro): delete obj pro
class Info():
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender


oneself = Info('HammerZe', 18, 'male')

# Find by string -- hasattr
print(hasattr(oneself, 'name'))  # --->True
print(hasattr(oneself, 'age'))  # --->True
print(hasattr(oneself, 'gender'))  # --->True

# Find by string -- getattr
print(getattr(oneself, 'name'))  # --->HammerZe
print(getattr(oneself, 'age'))  # --->18
print(getattr(oneself, 'gender'))  # --->male
# Find non-existent
print(getattr(oneself, 'weight', None))  # --->None
'''None It is only the default value and can be modified'''
print(getattr(oneself, 'weight', 140))  # --->140

# Modify by string
setattr(oneself, 'name', 'li')  # Equivalent to oneself name = 'li'
print(oneself.name)  # --->li

# Delete by string
delattr(oneself,'name')  # Equivalent to del oneself name
print(oneself.name) # --->AttributeError: 'Info' object has no attribute 'name'


Finally, thank you for reading. Each of your likes, comments and sharing is our greatest encouragement. Refill ~

If you have any questions, please discuss them in the comment area!

Keywords: Python Programming Back-end

Added by GroundZeroStudios on Wed, 05 Jan 2022 22:47:18 +0200