在python中,有什么方法可以在定义类后立即自动运行函数?

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)

jua*_*aga 6

处理这个问题的明智/简单的方法是让类的作者明确地做到这一点。所以像:

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)。

  • @bob.sacamento 再次,你可以使用装饰器/元类来制作一些奇特的东西,但是除非你期望相同的模式被重复使用很多次,否则我认为它不值得为代码添加精力和不透明性-根据。任何有能力的开发人员阅读上述内容,即使他们不懂 Python,也会明白发生了什么。这是我最近一直坚守的座右铭。尝试编写一些东西,以便那些有能力的开发人员但不会使用这种语言的人能够理解它。 (2认同)