flo*_*onk 5 python oop class-method
我有一个类,它包含一些成员x(例如,所有实例都需要但独立于它们的一些数据):
class Foo(object):
x = 23
# some more code goes here
Run Code Online (Sandbox Code Playgroud)
现在,确定的过程x变得更加复杂,而且我希望能够x在某些时间“刷新”,所以我决定为其编写一个额外的函数
class Foo(object):
@classmethod
def generate_x(cls):
cls.x = 23
# some more code goes here
Run Code Online (Sandbox Code Playgroud)
但是,该类定义缺少 的初始化调用generate_x。
到目前为止我尝试过的:
这不起作用:
class Foo(object):
# generate_x() # NameError: name 'generate_x' is not defined
# Foo.generate_x() # NameError: name 'Foo' is not defined
@classmethod
def generate_x(cls):
cls.x = 23
Run Code Online (Sandbox Code Playgroud)
这可行,但不太清楚,因为代码是在类定义之外使用的
class Foo(object):
@classmethod
def generate_x(cls):
cls.x = 23
# ...
Foo.generate_x()
Run Code Online (Sandbox Code Playgroud)
有更好的替代方案吗?这里使用的是@classmethod最好的方法吗?我正在搜索的是__init__.
考虑到代码清晰性,是否有比后者更好的方法来Foo.x使用函数自动实例化?
实现此目的的一种方法是使用装饰器:
def with_x(cls):
cls.generate_x()
return cls
@with_x
class Foo(object):
@classmethod
def generate_x(cls):
cls.x = 23
Run Code Online (Sandbox Code Playgroud)
(也就是说,我个人只会Foo.generate_x在类声明之后显式调用,并完全避免所有魔法。)