bob*_*nto 2 python class instantiation
我正在开发一个类。它将需要的类级数据将相对复杂。为了节省打字和减少错误,我想通过函数定义一些这些数据。此外,我想让用户可以使用这些数据,即使他们还没有准备好实例化该类。所以,我想知道,有没有办法让这些函数在定义类后立即自动运行?例如,我想要类似的东西
import numpy as np
def class foo:
@this_should_run_before_instantiation
def define_bar:
bar = np.range(100)
@this_should_also_run_before_init
def define_something_really complicated:
bleh = # something that is too complicated for a single line or lambda
def __init__(self):
# etc.
Run Code Online (Sandbox Code Playgroud)
那么用户可以做类似的事情
>>>from foopackage import foo
>>>foo.bar
array([ 0, 1, 2, 3, 4, 5, ... #etc.
>>>foo.bleh
< whatever bleh is ... >
Run Code Online (Sandbox Code Playgroud)
处理这个问题的明智/简单的方法是让类的作者明确地做到这一点。所以像:
class Foo:
@classmethod # don't have to be but will likely benefit from being classmethods...
def _define_something_really_complicated(cls):
...
@classmethod
def _define_something_else_really_complicated(cls):
...
@classmethod
def _build(cls):
cls._define_something_really_complicated()
cls._define_something_else_really_complicated()
...
def __init__(self):
...
Foo._build() # where your module is defined.
Run Code Online (Sandbox Code Playgroud)
然后每当消费者这样做时,import foo; my_foo_instance = foo.Foo()它就会被构建。
您可以创建一个元类来检查类成员的某个标签,它会自动执行此操作,但老实说,上面的内容对我和您类的未来读者来说非常清楚(最好不要将变量的初始化移动到看似神奇的地方)元类 foo)。
| 归档时间: |
|
| 查看次数: |
191 次 |
| 最近记录: |