问题描述
我正在尝试从类内部动态地为类变量分配一个值.
I am trying to dynamically assign a class variable a value from inside of a class.
class Test:
dynamic_value = get_dynamic_value()
我相信 get_dynamic_value()
应该属于 Test
类.有没有办法让 Test
包含这个方法?
I believe get_dynamic_value()
should belong to the Test
class. Is there a way to have Test
contain this method?
现在我正在使用并且它正在工作
Right now I am using and it is working
def get_dynamic_value():
return 'my dynamic value'
class Test:
dynamic_value = get_dynamic_value()
我希望 Test 包含此方法,因此我尝试使其成为 @classmethod
和 @staticmethod
并通过
I would like for Test to contain this method so I have tried to make it both a @classmethod
and a @staticmethod
and calling it by
class Test:
dynamic_value = Test.get_dynamic_value()
@staticmethod
def get_dynamic_value():
return 'dynamic'
但是当我使用静态方法尝试它时,我收到
But when trying it using a static method I receive
AttributeError: class Test 没有属性get_dynamic_value"
有没有办法做到这一点?或者有没有更好的方法来处理这个问题?
Is there any way to do this? Or is there a better way to handle this?
推荐答案
类套件自上而下求值,你定义的类要等到整个套件求值后才存在.
Class suites evaluate from top to bottom, and the class you are defining does not exist until after the entire suite is evaluated.
您可以将函数定义放在类体中,但是您必须在定义之后调用它,而不是之前.所以,这将起作用:
You can put the function definition inside the class body, but you've got to call it after it's been defined, not before. So, this will work:
class Test:
def get_dynamic_value():
return 'dynamic'
dynamic_value = get_dynamic_value()
不需要将函数标记为静态方法;它根本不用作方法,只是在类套件中评估期间调用的函数.如果您不希望该函数在定义类后可用(因为它不是一种方法),您可以将其删除.
Marking the function as a staticmethod is not necessary; it's not used as a method at all, just a function that is called during the evaluation in the class suite. If you don't want the function to be available after the class is defined (as it isn't intended as a method), you can delete it.
class Test:
def get_dynamic_value():
return 'dynamic'
dynamic_value = get_dynamic_value()
del get_dynamic_value
如果真的应该动态计算值,每次请求它(这样它就可以从访问更改为访问),那么您应该使用属性.
If the value is really supposed to be dynamically calculated, every time you ask for it (so it is able to change from access to access), then you should use a property.
class Test:
@property
def dynamic_value(self):
return 'dynamic'
这只会在访问类实例时进行评估,但属性对象本身将存在于类中.
This would only be evaluate when accessed on a class instance, but the property object itself would exist on the class.
这篇关于从类内部分配类变量动态值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!