#Learn Python # class functions, member functions, static functions, abstract functions, methods and camouflage properties

15, Class function, member function, static function, abstract function, method and attribute

This blog is the last blog in the second round of snowball learning python. We will continue to improve the content to the object-oriented part and supplement some decorators in the class for you. After learning, I hope your basic knowledge of Python can be improved.

15.1 class function @ classmethod

First look at the code directly, and then analyze and learn the content of the code.

class My_Class(object):

    # Define variables in class definitions
    cls_var = "Class variable"

    def __init__(self):
        print("Constructor")
        self.x = "The in the constructor belongs to an instance variable"

    # Class method. The first parameter must be passed to the class by default. Generally, cls is used.
    @classmethod
    def class_method(cls):
        print("class_method It is a class method, and the class name is called directly")
        # Class methods cannot call object variables (instance variables) inside a class
        # print(cls.x)

# Class methods can be called directly by class name or by object
# Even if a class method is called through an instance, Python automatically passes the class, not the instance
My_Class.class_method()
my_class_dom = My_Class()
# Object call through class
my_class_dom.class_method()

The first thing to master is the definition format of class functions. Add decorator @ classmethod in front of ordinary functions, and the function will be converted into class functions. At the same time, the first parameter of the function is cls by default. The variable name can be arbitrary. It is recommended to use cls. This is a convention between programmers.

 @classmethod
    def class_method(cls):

At the same time, class functions can be called by class name It can also be called through an object However, these two calls only pass the class to the function, and there is no difference.
Class functions cannot call instance variables, only class variables. The so-called class variables are variables that are independently declared in a class and do not appear in any function. In the above code, the code of class variable declaration is as follows:

class My_Class(object):
    # Define variables in class definitions
    cls_var = "Class variable"

In Python, the end of most @ classmethod decorated functions is return cls(XXX), return XXX__ new__ () that is, @ classmethod is mainly used as a constructor.

15.2 static function @ staticmethod

First master a concept. A static function does not belong to its class. It is a separate function independent of the class. It is just stored under a class name. First establish this basic concept, and then learn it much easier.

class My_Class(object):
    # Class variable
    cls_var = "Class variable"

    def __init__(self):
        # Create variable in constructor
        self.var = "Instance variable"

    # Ordinary object instance function
    def instance_method(self):
        # Can access class variables
        print(self.cls_var)
        # Can access instance variables
        print(self.var)
        print("Instantiation method")

    @staticmethod
    def static_method():
        print(My_Class.cls_var)
        # Unable to access instance variable
        # print(My_Class.var)
        # print(self.var)
        print("Static method")

my_class = My_Class()
my_class.instance_method()

# Access by object
my_class.static_method()
# Class name direct access
My_Class.static_method()

Even if it is modified to the following code, it is wrong. The first parameter of the static function is not the instance object self, or it can be understood that the static function has no hidden parameters. If you need to pass parameters, you can declare them in the parameter list.

    @staticmethod
    def static_method(self):
        print(My_Class.cls_var)
        # Unable to access instance variable
        # print(My_Class.var)
        print(self.var)
        print("Static method")

In the same class, the static method is called and the class name is used. Format of function name ().

15.3 performance of class functions and static functions in inherited classes

First create a parent class that contains two static functions and a class function.

class F(object):

    @staticmethod
    def f_static(x):
        print("Static method with 1 parameter")
        print(f"f_static: {x}")

    @staticmethod
    def f_static_1():
        print("Static method, no parameters")
        return F.f_static(10)

    @classmethod
    def class_method(cls):
        print("Class method in parent class")
        return F.f_static(12)

f = F()
f.f_static(11)
f.f_static_1()

f.class_method()

Write another S class to inherit from F class:

class S(F):

    @staticmethod
    def f_static(y):
        print("The static method of the parent class is overloaded in the subclass")
        print(f"Parameters in subclasses{y}")

    @classmethod
    def class_method(cls):
        print("Class methods in subclasses")

s = S()
s.f_static(110)
s.class_method()
S.class_method()

After the test, the basic conclusions are as follows:
If the static function of the parent class is overridden in the subclass, the static function of the subclass itself is used when calling,
If the static function of the parent class is not overridden in the subclass, the static function of the parent class is used when calling,
Class functions also follow this rule.

If you want to call the properties or functions of the parent class in the subclass, use the parent class name. In the form of.

15.4 abstract function @ abstractmethod

Functions decorated with @ abstractmethod are abstract functions. Classes containing abstract functions cannot be instantiated. Subclasses that inherit abstract functions must cover all methods decorated with abstract functions. Those that are not decorated may not be rewritten.

Abstract class is a special class. Its particularity is that it can only be inherited and cannot be instantiated. The implementation code is as follows:

import abc

class My_Class(abc.ABC):

    @abc.abstractmethod
    def abs_method(self):
        pass

    def show(self):
        print("ordinary")

class M(My_Class):
    def abs_method(self):
        print('xxx')

mm = M()
mm.abs_method()

Learning from abstract base classes also requires understanding metaclass related knowledge, which will be expanded for you in the third round of snowball learning Python.

15.5 method camouflage properties

In Python's object - oriented coding process, objects Property to get the value of the property, using the object Method (), a method can be masqueraded as a property through the decorator @ property, so as to use the object Method is called without parentheses. The code is very simple:

class My_Class(object):

    def __init__(self, name):
        self.__name = name

    @property
    def name(self):
        return self.__name

m = My_Class("eraser")
print(m.name)

The most direct application of this method is to change some attributes into read-only attributes. For example, in the above code, you cannot modify name through the following code.

class My_Class(object):
    def __init__(self, name):
        self.__name = name

    @property
    def name(self):
        return self.__name

m = My_Class("eraser")
m.name = "Wipe brother wipe sister"
print(m.name)

If you want the attributes disguised by the method to have the function of modification and deletion, you need to refer to the following code:

class My_Class(object):
    def __init__(self, name):
        self.__name = name

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, name):
        self.__name = name

    @name.deleter
    def name(self):
        del self.__name

m = My_Class("eraser")
m.name = "Wipe brother wipe sister"
print(m.name)

After the above code disguises the name method as an attribute, you can use @ name Setter and @ name The name method with the same name is decorated by the delete to realize the modification and deletion functions.

Therefore, the general steps of using methods to disguise attributes are:

  1. @The property decorator can be used to disguise the methods in the class as properties;
  2. @Method name setter decorator, which will be called when modifying the method value disguised as a property;
  3. @Method name The delete decorator, which is called when a method value disguised as a property is deleted.

If you find this troublesome, there is a way to disguise attributes. Using the property function, the prototype is as follows

# The last parameter is the string, which calls the instance Properties__ doc__  Description information when
property(fget=None, fset=None, fdel=None, doc=None)

The code that disguises the method as an attribute through the above function is:

class My_Class(object):
    def __init__(self, name):
        self.__name = name

    def del_name(self):
        del self.__name

    def set_name(self, name):
        self.__name = name

    def get_name(self):
        return self.__name
    # Disguise methods as properties
    name = property(get_name, set_name, del_name)
m = My_Class("Dream eraser")
print(m.name)
m.name = "eraser"
print(m.name)

del m.name

15.6 summary of this blog

The second round of 15 blogs on snowball learning Python ended at one time, and the next round will start again in mid April. We have been on the way to learn python. I hope this series of courses will help you learn python.

Keywords: Python Back-end

Added by khaitan_anuj on Sun, 26 Dec 2021 10:45:39 +0200