Python类构造函数(静态) [英] Python class constructor (static)

查看:159
本文介绍了Python类构造函数(静态)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python是否具有用于类构造函数的机制,即在首次引用该类时(而不是在创建该对象的实例时)调用的函数?我知道这在其他一些语言中也存在,但是我在Python中还没有遇到过。

Does Python have a mechanism for class constructors, i.e. a function that is called whenever the class is first referenced (as opposed to when an instance of that object is created)? I know this exists in some other languages, but I haven't come across it in Python.

基本上,我想在该函数中初始化一些静态属性。我在下面举例说明了我的期望。当然,该示例返回None,但是我希望它返回'foo'。

Basically, I would like to initialise some static attributes in that function. I put an example below of what I would expect. Of course, the example returns None, but I would like it return 'foo'.

class T:
    arg = None
    def __class_constructor__():
        T.arg = 'foo'

print(T.arg)  # returns None

为了避免混淆:我很了解对象构造函数,但这不是我想要的,因为只有在创建第一个对象后才调用它,

To avoid confusion: I am well aware of the object constructor, but that's not what I want, because it is only called once the first object is created, not before:

class T:
    arg = None
    def __init__(self):
        type(self).arg = 'foo'

print(T.arg)  # returns None
obj = T()
print(T.arg)  # returns 'foo'


推荐答案

您可以使用类装饰器:

def add_arg(cls):
    if not hasattr(cls, "arg"):
        cls.arg = 'foo'
    return cls

@add_arg
class T(object):
    pass

或自定义元类:

class WithArg(type):
    def __new__(meta, name, bases, attrs):
        cls = type.__new__(meta, name, bases, attrs)
        if not hasattr(cls, "arg"):
            cls.arg = "foo"
        return cls

# python 2
class T(object):
    __metaclass__ = WithArg

# python 3
class T(metaclass=WithArg):
    pass

但是正如其他人已经提到的那样,这与在class语句中简单地设置class属性相比,不会给您带来更多好处。

But as others already mention this won't give you much more than plainly setting the class attribute in the class statement.

NB:如果要在类本身上获得计算属性,则必须将其设置为自定义元类的属性

NB : if you want a computed attribute on the class itself, you'll have to either set it as a property on a custom metaclass

 class WithProp(type):
     @property
     def arg(cls):
         return "foo"

 class T(object):
     __metaclass__ = WithProp

 T.arg
 => 'foo'

但是 arg

T().arg
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'T' object has no attribute 'arg'

或编写您自己的自定义描述符:

or write your own custom descriptor:

class ArgDescriptor(object):
    def __get__(self, obj, cls=None):
        return 42

class T(object):
    arg = ArgDescriptor()

T.arg
=> 42
T().arg
=> 42

这篇关于Python类构造函数(静态)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆