InQ*_*ive 1 python python-decorators
编辑:我不是问什么是 classmethod 和 staticmethod 或它们之间的区别。只是问这个问题是为了澄清班级状态的含义。
\n\n我刚刚开始使用Python。在浏览@classmethod和的教程时@staticmethod,我在多个网站中发现了类似于以下内容的声明。
geekforgeeks中提到的
\n\n\n\n\n\n\n类方法可以访问或修改类状态,而静态方法\n 不能\xe2\x80\x99 访问或修改类状态。
\n
\n\n\n类方法可以访问和修改类状态。静态方法无法访问或修改类状态。
\n
阶级状态是什么意思?这是否意味着有一种方法可以使用类方法修改所有对象的值,因为当类状态更改时,它应该影响从该类创建的所有对象?我只能找到使用 @classmethods 创建工厂方法,并且我不认为这是某种类状态更改。
\n\nI am an advanced C++ programmer. Some related explanation would be good , if possible.
\n\nEdit: The question which marked this as duplicate of it doesn\'t mention the class states. I read both that questions and its duplicate before asking this.
\n\nOne example I tried:
\n\nclass MyClass:\n myvar = 100\n def __init__(self,age):\n self.myvar = age\n def instMethod(self):\n print("Inst method")\n\n @classmethod\n def classMethod(cls,age):\n cls.myvar = age\n\nobj1 = MyClass(10)\nobj2 = MyClass(20)\nobj3 = MyClass(30)\n\nprint(obj1.myvar)\nprint(obj2.myvar)\nprint(obj3.myvar)\n\nprint("after class method")\nMyClass.classMethod(45)\n\nprint(obj1.myvar)\nprint(obj2.myvar)\nprint(obj3.myvar)\nRun Code Online (Sandbox Code Playgroud)\n\noutput:
\n\n\n\n\n10
\n \n20
\n \n30
\n \nafter class method
\n \n10
\n \n20
\n \n30
\n
But my expectation was
\n\n\n\n10
\n \n20
\n \n30
\n \nafter class method
\n \n45
\n \n45
\n \n45
\n
Both of the explanations you have quoted are wrong. It is quite possible for a static method to modify the class's state:
class A:
x = 1
@staticmethod
def change_static():
A.x = 2
@classmethod
def change_class(cls):
cls.x = 3
Run Code Online (Sandbox Code Playgroud)
Proof:
>>> A.x
1
>>> A.change_static()
>>> A.x
2
>>> A.change_class()
>>> A.x
3
Run Code Online (Sandbox Code Playgroud)
The correct statement is that a class method takes an argument for the class it is called on, named cls in this example. This allows the class method to access the class it is called on (which may in general be a subclass of A), much like an instance method takes an argument usually named self in order to access the instance it is called on.
A static method takes no such argument, but can still access the class by name.
For the second half of your question, you need to understand how accessing an attribute on an instance works:
AttributeError将引发 an。请注意,这仅适用于获取属性的值;如果你设置了a.x = 23,那么你将始终设置属于a它自己的属性,即使它之前没有这样的属性。例如:
>>> A.x
1
>>> A.change_static()
>>> A.x
2
>>> A.change_class()
>>> A.x
3
Run Code Online (Sandbox Code Playgroud)
在您的代码中,该__init__方法设置该self.myvar属性,因此每个实例都有该属性。因此,类似的查找obj1.myvar永远不会回退到类的属性。
| 归档时间: |
|
| 查看次数: |
3321 次 |
| 最近记录: |