Eraser, one of the funny advanced Internet nerds. New series, let’s Be More Pythonic together.

Class function, member function, static function, abstract function, method disguise attribute

This blog is the last in the second round of snowballing Python. We will continue with the object-oriented section, adding some decorators to the classes, and hopefully improving your Basic Python knowledge.

15.1 Class functions @classMethod

Look directly at the code first, and then analyze and learn the content of the code.

class My_Class(object) :

    Define variables in the class definition
    cls_var = Class variable

    def __init__(self) :
        print("Constructor")
        self.x = "Belong to instance variable in constructor"

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


Class methods can be called either directly from the class name or from an object
Python automatically passes classes, not instances, even when class methods are called by instance
My_Class.class_method()
my_class_dom = My_Class()
# call through an object of the class
my_class_dom.class_method()
Copy the code

The first thing to master is the definition format of a class function. If you add the decorator @classmethod in front of a normal function, the function will be converted to a class function. At the same time, the first parameter of the function is CLS by default.

 @classmethod
    def class_method(cls) :
Copy the code

Also, class functions can be called by the class name. Can also be called through an object. However, both calls simply pass the class inside the function, there is no difference. Class functions cannot call instance variables, only class variables, the so-called class variables are declared independently in the class, do not appear in any function variables. In the above code, the class variable declaration part of the code is as follows:

class My_Class(object) :
    Define variables in the class definition
    cls_var = Class variable
Copy the code

In Python, most @classMethod functions end with return CLS (XXX). One of the main uses for return xxx.__new__ () is as a constructor.

15.2 @staticMethod

A static function does not belong to the class it belongs to. It is a separate function that is stored under the name of a class.

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

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

    # ordinary object instance function
    def instance_method(self) :
        Class variables can be accessed
        print(self.cls_var)
        Instance variables can be accessed
        print(self.var)
        print("Instantiation method")

    @staticmethod
    def static_method() :
        print(My_Class.cls_var)
        The instance variable cannot be accessed
        # 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()
Copy the code

The first argument to a static function is not the instance object self, or it has no hidden argument. If you need to pass an argument, declare it in the argument list.

    @staticmethod
    def static_method(self) :
        print(My_Class.cls_var)
        The instance variable cannot be accessed
        # print(My_Class.var)
        print(self.var)
        print("Static method")
Copy the code

In the same class, static methods are called, using the class name. The format of the function name ().

15.3 Representation of Class functions and static functions in inherited classes

Start by creating a parent class that contains two static functions and a class function.


class F(object) :

    @staticmethod
    def f_static(x) :
        print("Static method, one parameter.")
        print(F "f_static:{x}")

    @staticmethod
    def f_static_1() :
        print("Static method, no arguments.")
        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()
Copy the code

Write another S class that inherits from F:

class S(F) :

    @staticmethod
    def f_static(y) :
        print("A static method in a subclass overrides its parent class.")
        print(Parameter in f" subclass{y}")

    @classmethod
    def class_method(cls) :
        print("Class method in a subclass")


s = S()
s.f_static(110)
s.class_method()
S.class_method()
Copy the code

After testing, the basic conclusion is as follows: if a static function of the parent class is overridden in a subclass, the static function of the parent class is called. If a static function of the parent class is not overridden in a subclass, the static function of the parent class is called. Class functions also follow this rule.

If you want to call a property or function of the parent class in a subclass, use the parent class name. Form implementation.

15.4 Abstract function @abstractMethod

A function decorated with @abstractMethod is an abstract function. Classes containing abstract functions cannot be instantiated. Subclasses that inherit abstract functions must override all methods decorated with abstract functions.

Abstract class is a special class, which can only be inherited, can not be instantiated, 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()
Copy the code

Learning about abstract base classes also requires a knowledge of metaclasses, which will be covered in the third round of Snowballing Python.

15.5 Methods disguise properties

In Python object-oriented coding, objects. Property to get the value of the property, using the object. Method () to call a method, and the @property decorator lets you use objects by disguising a method as a property. 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)
Copy the code

The most direct use of this approach is to make some properties read-only. For example, in the above code, you cannot change the name by using 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 = "Fuck me, fuck me."
print(m.name)
Copy the code

If you want the properties of a method disguise to have modification and deletion capabilities, 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 = "Fuck me, fuck me."
print(m.name)
Copy the code

After masquerading the name method as an attribute, the above code can modify and delete the name method by decorating it with @name.setter and @name.deleter.

So the general steps for using method disguise properties are:

  1. @propertyDecorators, which can be used to disguise methods in a class as properties;
  2. At sign method name. SetterDecorator, called when modifying method values masquerading as properties;
  3. @method name.deleterDecorator, which is called when a method value masquerading as a property is deleted.

If you’re having trouble with this, there’s also a way to disguise attributes. Using the property function, the prototype is as follows

The last argument is a string, which calls the instance. Attribute.__doc__ description
property(fget=None, fset=None, fdel=None, doc=None)
Copy the code

The code for disguising a method as a property through the above functions 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
    Masquerade 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
Copy the code

15.6 Summary of this blog

The second round of 15 blogs in Python has ended in one session, and the next round will start again in mid-April. We are on our way to learning Python, so I hope this series of lessons helped you learn Python.

I’m the originator of the Eraser, Snowballing Python series. The third round will move into Python Web programming.

Blogger ID: Dream eraser, hope you like, comment, favorites.