python - Python中@classmethod的目的是什么?
问题描述
我目前正在学习 Python。@classmethod
在 OOP 中,装饰器的目的是什么?通过普通方法访问类变量和通过普通方法访问它有什么区别@classmethod
?就像我可以这样做一样:
class A():
_variable = A
def getVariable(self):
return self._variable
或者
class A():
_variable = A
@classmethod
def getVariable(cls):
return cls._variable
两种方法有什么区别?为什么我需要使用什么时候使用classmethod,什么时候不需要?如果我不这样做会怎样?
解决方案
使用类和实例变量/方法时,您关心的是可见性!
类变量/方法由类的所有实例共享,而实例变量/方法仅对您现在拥有的实例可用!
一般来说,实例变量用于每个实例唯一的数据,类变量用于类的所有实例共享的属性和方法:python教程
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind # shared by all dogs
'canine'
>>> e.kind # shared by all dogs
'canine'
>>> d.name # unique to d
'Fido'
>>> e.name # unique to e
'Buddy'
这个例子没有向你展示的是,使用类方法,你可以在不通过实例的情况下调用类上的方法!
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
@classmethod
def isGoodBoy(cls):
return True # all dogs are good boys!
现在该isGoodBoy
方法不需要访问狗的名字,所以它可以是一个类方法,这反映在所有实例上;毕竟所有的狗都是好男孩(和女孩!)。
但这告诉你更多!狗是好孩子吗?我们是否要求任何特定的狗成为一个好孩子?
>> Dog.isGoodBoy() # here we call the method on the class
True # debate settled!
现在有四个你的其他问题;当你处理类而不是对象时,最好有一个类方法。您如何知道记录器实例在创建之前是否需要网络?这就是类方法和类变量的用途,以及该类的所有对象的共同状态和行为。
现在,由于这是在所有类之间共享的,因此您现在遇到了其他问题,该类的每个实例都可能修改类变量!这也意味着您可以在没有对象的情况下查询变量值!
假设您想在运行时从方法 A 切换到方法 B。
class Foo:
upgrade = False
def a(self):
...
def b(self):
...
def run(self):
self.a() if self.upgrade else self.b()
现在Foo.upgrade = True
将为每个人更换东西!或者甚至更好地通过跑步让狗变成猫科动物Dog.kind = 'feline'
推荐阅读
- url - 使用 PowerMockito 模拟 URL 和 HttpURLConnection
- python - 将 Pandas 数据框分成两部分
- javascript - 电子 jquery.easing 不是一个函数
- java - 使用 mockito 以否定方法编写测试用例
- apache-spark - 在哪里可以看到 Spark 中的任务指标
- jquery - 只需选择文件而不提交表单即可上传文件
- swift - 单元格 UICollectionViewLayout 之间的空间
- javascript - ckeditor 4.9.2 instanceDestroyed 事件没有被触发
- sql-server - ] 符号的 mssql patindex
- kubernetes - 有没有办法在 pod 规范中获取 UID