Python全栈工程师

27.4-类方法和静态方法装饰器

2019-12-05  本文已影响0人  BeautifulSoulpy

昨天你是谁不重要,重要的是今天你是谁,以及明天你将成为谁!

总结:

  1. 写装饰器先写等价式;
  2. 类几乎可以调用所有内部定义的方法,但是调用 普通的方法 时会报错,原因是第一参数必须是类的实例。实例也几乎可以调用所有的方法, 普通的函数 的调用一般不可能出现,因为不允许这么定义。
  3. 类除了普通方法都可以调用,普通方法需要对象的实例作为第一参数。
  4. 实例 self 的属性是放在实例的字典中的,类 cls 的属性是放在类的字典当中的;

参考:python 实例方法、类方法、静态方法区别

1. Python 实例方法、类方法、静态方法区别

实例方法
定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法);
调用:只能由实例对象调用。

类方法
定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法);
调用:实例对象和类对象都可以调用。

静态方法
定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法;
调用:实例对象和类对象都可以调用。

如何装饰一个类; 不是装饰器类(本身是装饰器);

def add_name(cls,name='jerry'):  # 无参装饰器;
    cls.NAME = name
    return cls

def add_name(name='jerry'):     # 有参装饰器;
    def wrapper(cls):
        cls.NAME = name
        return cls
    return wrapper

# 为类增加一些类属性;
@add_name(name='tom')
class Person: # Person = wrapper(Person)
    AGE = 20
    
    def __init_(self):
        self.name = 'tom'
    
print(Person.__dict__.items())
#--------------------------------------------------------------
dict_items([('__module__', '__main__'), ('AGE', 20), ('_Person__init_', <function Person.__init_ at 0x000002D3409C9E18>), 
('__dict__', <attribute '__dict__' of 'Person' objects>), ('__weakref__', <attribute '__weakref__' of 'Person' objects>), ('__doc__', None), ('NAME', 'tom')])


Python 可以给类装饰,但是可不可以给 实例 装饰呢?
如何用类装饰另一个类;

2. 类中的三种方法: 普通方法(多),类方法(多),静态方法

面的例子中定义的 _init_ 等方法,这些方法本身都是类的属性,第一个参数必须是self,而self必须指向一个对象,也就是类必须实例化之后,由实例来调用这个方法。

普通函数
#  普通函数 
class Person:
    def normal_method(): # 禁止使用,;
        print('normal')
        
    def method(self):   # 普通方法;
        print(self)
        
Person.normal_method()
# Person().normal_method()  # 实例调用 必须要一个参数self本身;
print(Person.__dict__)      
print('-'*120)
# 类来传参;
Person.method(Person())   # Person() 实例本身;
Person.method(123)  # 普通函数 调用;

# 实例化
Person().method()
#--------------------------------------------------------------------------
normal
{'__module__': '__main__', 'normal_method': <function Person.normal_method at 0x0000023B63CFD950>, 'method': <function Person.method at 0x0000023B63E80488>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
------------------------------------------------------------------------------------------------------------------------
<__main__.Person object at 0x0000023B63F64780>
123
<__main__.Person object at 0x0000023B63F64780>

Person.normal_method()

  1. 可以放在类中定义,因 这个方法是Person这个名词空间管理的方法;normal_method是Person的一个属性而已。
  2. 由于normal_method在定义的时候没有指定self,所以不能完成实例对象的绑定,不能用Person().normal_method()调用。
    注意:虽然语法是对的,但是,没有人这么用,也就是说禁止这么写

类方法 classmethod(变为一个类)

该装饰器能将类中定义的方法变成类方法,类方法的第一个参数必须是cls,cls是对该类的引用,通过cls对类的属性进行访问;能够通过类或类的实例对象来调用类方法。
传入的第一参数是 class类;

  1. 在类定义中,使用@classmethod装饰器修饰的方法
  2. 必须至少有一个参数,且第一个参数留给了cls(必须是类),cls指代调用者即类对象自身
  3. cls这个标识符可以是任意合法名称,但是为了易读,请不要修改
  4. 通过cls可以直接操作类的属性
    注意:无法通过cls操作类的实例。为什么?
class Person:
    def normal_method(): # 禁止使用,普通函数;
        print('normal')
    
    def method(self):   # 普通方法
        print(self)
        
    @classmethod  #   类方法  :看当前是  实例 还是 类;
    def class_method(cls):
        print('class method',cls,hex(id(cls)),hex(id(Person)))
Person.normal_method()
# Person().normal_method()  # 实例调用 必须要一个参数self本身;
print(Person.__dict__)      
print('-'*120)

# 实例化
p1 = Person()
print(hex(id(p1)))
#p1.normal_method()
p1.class_method()
Person.class_method()
#---------------------------------------------------------------
normal
{'__module__': '__main__', 'normal_method': <function Person.normal_method at 0x0000023B63FC17B8>, 'method': <function Person.method at 0x0000023B63FC10D0>, 'class_method': <classmethod object at 0x0000023B63F73C88>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
------------------------------------------------------------------------------------------------------------------------
0x23b63f73438
class method <class '__main__.Person'> 0x23b623a6038 0x23b623a6038
class method <class '__main__.Person'> 0x23b623a6038 0x23b623a6038

静态方法 staticmethod_改变行为

该装饰器能将类中定义的方法变成静态方法,静态方法不需要传入self参数,基本和全局函数差不多;能够通过类或类的实例对象来调用静态方法。

  1. 在类定义中,使用@staticmethod 装饰器修饰的方法;
  2. 调用时,不会隐式的传入参数;
    静态方法,只是表明这个方法属于这个名词空间;函数归在一起,方便组织管理;
#  静态方法;staticmethod
class Person:
    def normal_method(): # 禁止使用,普通函数;
        print('normal')
    
    def method(self):  # 普通方法;
        print(self)
        
    @classmethod  #   类方法:
    def class_method(cls):  #看当前是  实例 还是 类;
        print('class method',cls,hex(id(cls)),hex(id(Person)))
        
    @staticmethod    # 静态方法
    def static_method():
        print('static method')
        


Person.normal_method()
# Person().normal_method()  # 实例调用 必须要一个参数self本身;
print(Person.__dict__)      
print('-'*120)

# 实例化
p1 = Person()
print(hex(id(p1)))
#p1.normal_method()
p1.class_method()
Person.class_method()

Person.static_method()   # 都不会传入多余的参数;
Person().static_method()
#-------------------------------------------------------------------------------------------------------
normal
{'__module__': '__main__', 'normal_method': <function Person.normal_method at 0x0000023B63E80488>, 'method': <function Person.method at 0x0000023B63FEBAE8>, 'class_method': <classmethod object at 0x0000023B63F78E80>, 'static_method': <staticmethod object at 0x0000023B63F78A90>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
------------------------------------------------------------------------------------------------------------------------
0x23b63f780f0
class method <class '__main__.Person'> 0x23b6239f198 0x23b6239f198
class method <class '__main__.Person'> 0x23b6239f198 0x23b6239f198
static method
static method



# 进阶方法;

class Person:
    X = 13  # 所有类的访问都是通过 类的实例 进行访问;
    def normal_method(): # 禁止使用,普通函数;
        print('normal')
    
    def method(self):  # 普通方法;
        print(self)
        
    @classmethod  #   类方法:
    def class_method(cls):  #看当前是  实例 还是 类;
        print('class method',cls,hex(id(cls)),hex(id(Person)))
        print(cls.X)
        
    @staticmethod    # 静态方法
    def static_method(cls):
        print('static method',cls)
        print(cls.x)
        print(Person.X)  # 静态方法 ,通过类来访问;

print('~~~~类访问')
print(1, Person.normal_method()) # 可以吗
print(2, Person.method()) # 不可以吗,没参数
print(3, Person.class_method()) # 可以吗print('~~~~类访问')
print(1, Person.normal_method()) # 可以吗
print(2, Person.method()) # 可以吗
print(3, Person.class_method()) # 可以吗
print(4, Person.static_methd()) # 可以吗
print(Person.__dict__)

print('~~~~实例访问')
print('tom----')
tom = Person()
print(1, tom.normal_method()) # 不可以吗
print(2, tom.method()) # 可以吗
print(3, tom.class_method()) # 可以吗?
print(4, tom.static_methd()) # 可以吗

print('jerry----')
jerry = Person()
print(1, jerry.normal_method()) # 不可以吗
print(2, jerry.method()) # 可以吗
print(3, jerry.class_method()) # 可以吗?
print(4, jerry.static_methd()) # 可以吗


总结:

  1. 类几乎可以调用所有内部定义的方法,但是调用 普通的方法 时会报错,原因是第一参数必须是类的实例。
    实例也几乎可以调用所有的方法, 普通的函数 的调用一般不可能出现,因为不允许这么定义。
  2. 类除了普通方法都可以调用,普通方法需要对象的实例作为第一参数。>
  3. 实例可以调用所有类中定义的方法(包括类方法、静态方法),普通方法传入实例本身,静态方法和类方法需要找到实例的类。

实例方法与静态方法 区别

一、先是在语法上面的区别:
1、静态方法不需要传入self参数,类成员方法需要传入代表本类的cls参数;
2、静态方法是无妨访问实例变量和类变量的,类成员方法无法访问实例变量但是可以访问类变量

二、使用的区别:
由于静态方法无法访问类属性,实例属性,相当于一个相对独立的方法,跟类其实并没有什么关系。这样说来,静态方法就是在类的作用域里的函数而已。

三. 调用区别

  1. 调用上实例方法不能直接被类调用
class Person:
    X = 13  # 所有类的访问都是通过 类的实例 进行访问;
    def normal_method(): # 禁止使用,普通函数;
        print('normal')
    
    def method(self):  # 普通方法;
        print(self)
        
    @classmethod  #   类方法:
    def class_method(cls):  #看当前是  实例 还是 类;
        print('class method',cls,hex(id(cls)),hex(id(Person)))
        print(cls.X)
        
    @staticmethod    # 静态方法
    def static_method():
        print('static method')
        #print(cls)
        print(Person.X)
        
Person.method(Person())
Person().method()

Person().class_method()
Person.class_method()

Person.static_method()
Person().static_method()
# ------------------------------------------------------------------------------
<__main__.Person object at 0x0000023B63FCEB70>
<__main__.Person object at 0x0000023B63FCECC0>
class method <class '__main__.Person'> 0x23b623a6ef8 0x23b623a6ef8
13
class method <class '__main__.Person'> 0x23b623a6ef8 0x23b623a6ef8
13
static method
13
static method
13






class Person:
    X = 13  # 所有类的访问都是通过 类的实例 进行访问;
    def normal_method(): # 禁止使用,普通函数;
        print('normal')
    
    def method(self,name):  # 普通方法;
        print(self)
        
    @classmethod  #   类方法:
    def class_method(cls,age):  #看当前是  实例 还是 类;
        print('class method',cls,hex(id(cls)),hex(id(Person)))
        print(cls.X)
        
    @staticmethod    # 静态方法
    def static_method(a):
        print('static method',a)
        #print(cls)
        print(Person.X)
        
Person.method(Person(),'ken')  # 不会自动传入,自己传Person()
Person().method('ken')    # 第一参数自动传入Person()

Person().class_method(18)  # cls
Person.class_method(20)    # cls

Person.static_method(1)
Person().static_method(2)
#--------------------------------------------------------------
<__main__.Person object at 0x0000023B6404A518>
<__main__.Person object at 0x0000023B6404A630>
class method <class '__main__.Person'> 0x23b6239f548 0x23b6239f548
13
class method <class '__main__.Person'> 0x23b6239f548 0x23b6239f548
13
static method 1
13
static method 2
13


上一篇下一篇

猜你喜欢

热点阅读