如何使用 class 方法初始化 class 成员
How to initialize a class member using a classmethod
我有一个 class,它包含一些成员 x
(例如,所有实例都需要但独立于它们的一些数据):
class Foo(object):
x = 23
# some more code goes here
现在,确定 x
的过程变得更加复杂,而且我希望能够在特定时间 "refresh" x
,所以我决定为其编写一个额外的函数
class Foo(object):
@classmethod
def generate_x(cls):
cls.x = 23
# some more code goes here
但是,此 class 定义缺少 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
这有效但不太清楚,因为代码在 class 定义之外使用
class Foo(object):
@classmethod
def generate_x(cls):
cls.x = 23
# ...
Foo.generate_x()
有没有更好的替代方案?使用 @classmethod
是最好的方法吗?我正在搜索的是 class 等价于 __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
(也就是说,我个人会在 class 声明之后显式调用 Foo.generate_x
,并完全避免所有魔法。)
使用描述符。
class Complicated:
def __init__(self, location, get_value):
self.location =location
self.get_value = staticmethod(get_value)
def __get__(self, obj, owner):
try:
a = getattr(owner, self.location)
except AttributeError:
a = self.get_value()
setattr(owner, self.location, a)
return a
class My class:
x = Complicated ('_x', get_x)
我有一个 class,它包含一些成员 x
(例如,所有实例都需要但独立于它们的一些数据):
class Foo(object):
x = 23
# some more code goes here
现在,确定 x
的过程变得更加复杂,而且我希望能够在特定时间 "refresh" x
,所以我决定为其编写一个额外的函数
class Foo(object):
@classmethod
def generate_x(cls):
cls.x = 23
# some more code goes here
但是,此 class 定义缺少 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
这有效但不太清楚,因为代码在 class 定义之外使用
class Foo(object):
@classmethod
def generate_x(cls):
cls.x = 23
# ...
Foo.generate_x()
有没有更好的替代方案?使用 @classmethod
是最好的方法吗?我正在搜索的是 class 等价于 __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
(也就是说,我个人会在 class 声明之后显式调用 Foo.generate_x
,并完全避免所有魔法。)
使用描述符。
class Complicated:
def __init__(self, location, get_value):
self.location =location
self.get_value = staticmethod(get_value)
def __get__(self, obj, owner):
try:
a = getattr(owner, self.location)
except AttributeError:
a = self.get_value()
setattr(owner, self.location, a)
return a
class My class:
x = Complicated ('_x', get_x)