Completed projects

My construction plan

2. Digital Topics

3 String Topics

4 List topics

5 process control topics

6 programming style topics

7 Function Usage

8. Object-oriented Programming (Part I)

The previous article on OBJECT-ORIENTED programming (part 1) discussed the basics of object-oriented programming, using cases to explain three features: encapsulation, inheritance, and polymorphism.

Today we continue the advanced part of object-oriented programming

Advanced topics

1 Create an abstract method

In the previous section on polymorphism, we defined the base class module animals2.py with a method called getSpeedBehavior, which was overridden in the two inherited classes. While this mode does not report errors, it is not optimal programming.

class Animal():
   cprop = "I am a property cprop on a class"Def __str__(self,name,speed): self. Name = name # self.return ' ''Animal({0.name},{0._speed}) is printed name={0.name} speed={0._speed}'' '.format(self)

   def getSpeedBehavior(self):
       pass 
Copy the code

Even better, display the method that defines the base class as abstract and explicitly name the two inherited classes that need to override the method.

With Python’s built-in ABC module, using an AbstractMethod decorator, an improved version of the Animal class:

import abc

class Animal():
   cprop = "I am a property cprop on a class"Def __str__(self,name,speed): self. Name = name # self.return ' ''Animal({0.name},{0._speed}) is printed name={0.name} speed={0._speed}'' '@abc.abstractmethod def getSpeedBehavior(self): passCopy the code

None of the other classes change. That’s how you create an abstract class.

2 Check the attribute value

We have defined two attributes name and _speed in the Animal class:

class Animal():
   cprop = "I am a property cprop on a class"Def __init__(self,name,speed): __init__(self,name,speed): selfCopy the code

For attributes defined in this way, it is not reasonable for outsiders to assign arbitrary values to the attributes. The following speed parameter is assigned a negative value, which is definitely not reasonable:

jiafeimao = Cat('jiafeimao'.2 -.'gray'.'CatGenre')
Copy the code

So one solution is to use @property, which is also very succinct:

@property def _speed(self):returnSelf.__speed # write @_speed. Setter def _speed(self,val):if val < 0:
           raise ValueError('speed value is negative')
       self.__speed = val
Copy the code

When Cat(‘ jiafeiMAO ‘,-2,’gray’,’CatGenre’) is executed, it goes to @_spee. setter, checks for any exception, and throws a value exception.

@property is a function that adds functionality to _speed and returns a more powerful function, @property. Setter is also a function that decorates and controls writing to properties.

3 Add attributes to the class

Adding attributes to an instance, as mentioned in the basic article, only applies to that instance. Other attributes still do not have this attribute. How do you add attributes outside once, and all instances have them?

Add an age attribute to the Cat class, as shown below. Jiafeimao instances and JiQIMAO instances both have an age attribute and can be modified:

if __name__ == "__main__":
    jiafeimao = Cat('jiafeimao'.2.'gray'.'CatGenre')
    
    Cat.age = 1
    jiafeimao.age = 3
    print(jiafeimao.age) # 3 
    jiqimao = Cat('jiqimao'.3.'dark'.'CatGenre')
    jiqimao.age = 5
    print(jiqimao.age) # 5
Copy the code

This means that if you add one attribute to a class at a time, all instances of the class will have the new attribute.

While this is convenient to write, it has the side effect that supporting dynamic addition actually breaks the encapsulation of classes and makes maintenance programs difficult. At the same time, if the use of excessive attributes will become large memory, affecting the performance of the program.

4 Control adding attributes at will

Python should be aware of the side effects of adding attributes dynamically above, and therefore set aside a system magic function __slots__ to control arbitrary addition of attributes.

Using __slots__, define which attributes the class can have. Attributes that are not in the tuple will fail to be added.

Controls that the Student class can only have attributes name and age, and no other attributes are allowed:

class Student(object):
    __slots__ = ('name'.'age'Def __init__(self,name,age): self. Name = name self. Age = age s = Student() def __init__(self,name,age): self.'xiaoming'.100) # create a new instance10
Copy the code

The following exceptions occur:

5 Chain call

Each method that is exposed returns self, so that when called externally, it forms a chain of calls, a style you can see in frameworks like Pyecharts.

class Student(object):
    __slots__ = ('name'.'age'Def __init__(self,name,age): self.name = name self.age = age def set_name(self,val): self.name = valreturn self 
    
    def set_age(self,age):
        self.age = age 
        return self
    
    def print_info(self):
        print("name: "+self.name)
        print("age: "+ str(self.age))
        return self
 
s = Student('xiaoming'.100# create a new instance (s.set_name ('xiaoming1')
    .set_age(25)
    .print_info()
)
Copy the code

There is another important design principle for the more advanced part of object-oriented programming: the MixIn principle, which we will discuss later when we talk about design patterns.

The above is the advanced part of object-oriented programming, the original is not easy, welcome three support.

Highlights of past For beginners entry route of artificial intelligence and data download machine learning and deep learning notes such as printing machine learning online manual deep learning notes album "statistical learning method" code retrieval based album album download AI based machine learning math to get a sale station knowledge star coupons, copy the link directly open: HTTPS://t.zsxq.com/662nyZF site QQ group 1003271085. To join the wechat group, please scan the code and enter the group (please specify if you have a PhD or are planning to study for a PhD) :
Copy the code