程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python class function, member function, static function, abstract function, method camouflage attribute

編輯:Python

15、 ... and 、 Class function 、 Member functions 、 Static functions 、 Abstract functions 、 Method camouflage properties

This blog is about snowballing Python The last blog in the second round , Let's move on to the object-oriented part of the content , For you to add some decorations in the class , After learning , I hope your Python Basic knowledge can go a step further .

15.1 Class function @classmethod


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

class My_Class(object):
# Define variables in class definitions
cls_var = " Class variables "
def __init__(self):
print(" Constructors ")
self.x = " The variables in the constructor belong to instance variables "
# Class method , The first parameter must be passed to the class by default , I'm used to cls.
@classmethod
def class_method(cls):
print("class_method Is a class method , Class name directly calls ")
# Class methods cannot call object variables inside a class ( Instance variables )
# print(cls.x)
# Class methods can be called directly through the class name , You can also call
# Even if class methods are called through instances ,Python Classes are also passed automatically , Not an instance
My_Class.class_method()
my_class_dom = My_Class()
# Through the object call of class
my_class_dom.class_method()

The first thing to master is the definition format of class function , Add decorators in front of normal functions @classmethod, The function will be converted to a class function , At the same time, the first parameter of the function is cls, The variable name can be any , It is suggested that cls, This is a contract between programmers .

 @classmethod
def class_method(cls):

At the same time, when class functions are called , Can pass Class name . Call in the form of , It can also be done through object . Form call of , But both of these calls just pass the class inside the function , There is no difference .

Class functions cannot call instance variables , Only classes can be called , So-called Class variables That is, to declare independently in a class , Variables that don't appear in any function . In the above code , Class variable declaration part of the code is as follows :

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

stay Python in , Most of the @classmethod Decorated functions end with return cls(XXX), return XXX.__new__ () That is to say @classmethod One of the main uses of is as a constructor .

15.2 Static functions @staticmethod


First grasp a concept , Static functions don't belong to the class they are in , It's a separate function independent of the class , It's just registered under a class name , Let's start with this basic concept , It's much easier to learn later .

class My_Class(object):
# Class variables
cls_var = " Class variables "
def __init__(self):
# Create variables in the constructor
self.var = " Instance variables "
# Common object instance functions
def instance_method(self):
# Class variables can be accessed
print(self.cls_var)
# You can access instance variables
print(self.var)
print(" Instantiation method ")
@staticmethod
def static_method():
print(My_Class.cls_var)
# Cannot access instance variable
# print(My_Class.var)
# print(self.var)
print(" Static methods ")
my_class = My_Class()
my_class.instance_method()
# Object access
my_class.static_method()
# Class name direct access
My_Class.static_method()

Even if changed to the following code , It's also wrong , The first argument to a static function is not an instance object self, Or it can be understood that static functions have no hidden parameters , If you need to pass parameters , Just declare it in the parameter list .

 @staticmethod
def static_method(self):
print(My_Class.cls_var)
# Cannot access instance variable
# print(My_Class.var)
print(self.var)
print(" Static methods ")

In the same class , Call static methods , Use Class name . Function name () The format of .

15.3 The representation of class function and static function in inheritance class


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

class F(object):
@staticmethod
def f_static(x):
print(" Static methods , Yes 1 Parameters ")
print(f"f_static:{x}")
@staticmethod
def f_static_1():
print(" Static methods , No parameter ")
return F.f_static(10)
@classmethod
def class_method(cls):
print(" Class methods in the parent class ")
return F.f_static(12)
f = F()
f.f_static(11)
f.f_static_1()
f.class_method()

Write another S Class inherits 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 covered in the subclass , The static function of the subclass is used when calling ,

If there is no static function that covers the parent class in the subclass , That call uses the static function of the parent class ,

Class functions also follow this rule .

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

15.4 Abstract functions @abstractmethod


By @abstractmethod Decorated functions are abstract functions , Classes with abstract functions cannot be instantiated , Inheriting subclasses containing abstract functions must cover all methods decorated with abstract functions , What is not decorated can not be rewritten .

Abstract class is a special class , Its specialty is that it can only be inherited , Can't 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 knowledge about metaclasses , In the third round of snowballing Python I will expand this part for you .

15.5 Method camouflage properties


stay Python In the process of object-oriented coding , object . attribute To get the value of the property , Use object . Method () To call methods , Through ornaments @property You can disguise a method as a property , To use object . Method Call 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 writing method is , That is to make some attributes read-only , for example , The above code , You can't use the following code to name Make changes .

class My_Class(object):
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
m = My_Class(" Eraser ")
m.name = " Brother and sister "
print(m.name)

If you want the properties disguised by the method to have the function of modifying and deleting , 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 = " Brother and sister "
print(m.name)

The above code will name Methods disguised as properties , Can pass @name.setter and @name.deleter For the same name name How to decorate , Thus, the function of modification and deletion is realized .

So the general steps to camouflage attributes are :

  1. @property Decorator , Can be used to disguise methods in a class as properties ;
  2. @ Method name .setter Decorator , It is called when you modify the value of a method disguised as a property ;
  3. @ Method name .deleter Decorator , It is called when a method value disguised as a property is deleted .

If you think this is more troublesome , There is also a way to camouflage attributes . Use property function , The prototype is as follows

# The last parameter is the string , call example . attribute .__doc__ The description of the time
property(fget=None, fset=None, fdel=None, doc=None)

The code to disguise a 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 a method as a property
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 The summary of this blog


Snowballing Python The second round 15 This blog is over at one time , The next round will be in 4 It will open again in the middle of this month , learn Python We've been on the road , I hope this series of courses is helpful to your Python Learning helps .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved