简体   繁体   English

Python 3的静态类属性

[英]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.FooMyClass.Bar调用方法_foo_func_bar_func

Note that the custom descriptor object, the second answer in the linked question, is: 请注意,自定义描述符对象(链接问题中的第二个答案)是:

  1. More portable granted you explicitly inherit from object in your class definitions. 授予您更多可移植性,您可以从类定义中的object显式继承。
  2. More maintainable than creating a custom metaclass. 比创建自定义元类更具维护性。 Metaclasses might lead to confusion and weird conflicts down the line, descriptors are simple after you get a hang of them 元类可能会导致混乱和奇怪的冲突,在您掌握了它们之后,描述符很简单

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM