[英]Static class attributes with Python 3
I need to define custom attributes for a class, but redefining __getattr__
works only for the instance, not for the class itself, and making it static doesn't really help. 我需要为类定义自定义属性,但是重新定义
__getattr__
仅适用于实例,不适用于类本身,并且将其设置为静态并没有真正的帮助。 I know that something like this works for Python 2, but I couldn't find anything similar on Python 3, I suspect due to changing the way metaclasses work. 我知道,像这样的作品为Python 2,但我找不到关于Python 3类似的话,我怀疑是由于改变元类的工作方式。 How would I achieve similar result?
我如何获得类似的结果?
You need to change the way you specify metaclasses in Python 3. It was changed from a dunder attribute __metaclass__
to a kwarg
you supply after the base classes. 您需要更改在Python 3中指定元类的方式。它已从dunder属性
__metaclass__
更改为在基类之后提供的kwarg
。 Other than that, the solution provided there suffices: 除此之外,这里提供的解决方案就足够了:
class MyClass(metaclass = FooType): pass
Now MyClass.Foo
or MyClass.Bar
call the methods _foo_func
and _bar_func
respectively. 现在,
MyClass.Foo
或MyClass.Bar
调用方法_foo_func
和_bar_func
。
Note that the custom descriptor object, the second answer in the linked question, is: 请注意,自定义描述符对象(链接问题中的第二个答案)是:
object
in your class definitions. object
显式继承。 Adding to Jims answer: If you need Python2 and 3 compatibility you can use the six.add_metaclass
class decorator: 添加到Jims答案:如果您需要Python2和3兼容性,则可以使用
six.add_metaclass
类装饰器:
import six
@six.add_metaclass(your_metaclass)
class Yourclass(): # no need to add "metaclass = your_metaclass" here!
# no need to define "__metaclass__ = your_metaclass" here
Like the documentation states, this: 像文档状态一样:
@six.add_metaclass(Meta)
class MyClass(object):
pass
is identical to (python2): 与(python2)相同:
class MyClass(object):
__metaclass__ = Meta
or (python3): 或(python3):
class MyClass(object, metaclass=Meta):
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.