我正在使用Python2.7
我想知道在Python中,是否可以在模块级别添加代码来初始化模块中包含的类。
class DoSomething(object):
foo = 0
bar = 0
@classmethod
def set_all_to_five(cls):
cls.bar = 5
cls.foo = 5
@classmethod
def set_all_to_ten(cls):
cls.bar = 10
cls.foo = 10
#Module level code - runs on import of the class DoSomething
DoSomething.set_all_to_five()输出:
>>> from productX.moduleY import DoSomething
>>> print DoSomething.bar
5这个类只包含@classmethod方法,所以我可以调用它们,而不必实例化类。
模块级code DoSomething.set_all_to_5()在导入模块时初始化类级属性。
发布于 2018-04-02 16:00:19
在模块级别添加代码以初始化模块中包含的类可以吗?
是的,你所拥有的一切都很好。当人们将“动态”描述为一种动态语言时,这就是这个词的意思:,您可以在运行时中更改类型的定义。定义类的整个模块必须在使用DoSomething名称之前成功导入,因此不可能有人意外地使用类的“未修补”版本。
但是,如果希望类的行为完全在类块中定义,而不是在类定义之后应用"monkeypatch“,则可以使用其他一些选项。
使用元类
class DoSomethingMeta(type):
def __init__(self, name, bases, attrs):
super(DoSomethingMeta, self).__init__(name, bases, attrs)
self.set_all_to_five()
class DoSomething(object):
__metaclass__ = DoSomethingMeta # for Python3, pass metaclass kwarg instead
foo = 0
bar = 0
@classmethod
def set_all_to_five(cls):
cls.bar = 5
cls.foo = 5
@classmethod
def set_all_to_ten(cls):
cls.bar = 10
cls.foo = 10或者,更简单地说,使用装饰器
def mydecorator(cls):
cls.set_all_to_five()
return cls
@mydecorator
class DoSomething(object):
....https://stackoverflow.com/questions/49614245
复制相似问题