__getAttr __用于静态/类变量
我有一个类似的类:
class MyClass:
Foo = 1
Bar = 2
每当myClass.foo
或myClass.bar
被调用时,我都需要一种自定义方法才能在返回该值之前被调用。在Python中有可能吗?我知道,如果我创建一个类的实例,我可以定义自己的__ getAttr __
方法。但是我的scnenario涉及使用此类而没有创建任何实例。
另外,当调用str(myClass.foo)
时,我需要调用一个自定义__ str __
方法。 Python是否提供了这样的选择?
I have a class like:
class MyClass:
Foo = 1
Bar = 2
Whenever MyClass.Foo
or MyClass.Bar
is invoked, I need a custom method to be invoked before the value is returned. Is it possible in Python? I know it is possible if I create an instance of the class and I can define my own __getattr__
method. But my scnenario involves using this class as such without creating any instance of it.
Also I need a custom __str__
method to be invoked when str(MyClass.Foo)
is invoked. Does Python provide such an option?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
__ getAttr __()
和__ str __()
在其类上找到一个对象,因此,如果您想自定义类别的类别,则需要 - -班级。一个元素。打印:
不,一个对象无法拦截一个符合其属性之一的请求。返回的属性对象必须定义其自己的
__ str __()
行为。更新了Python 3.x默认实现的2023-02-20(Python 2作为评论)。
__getattr__()
and__str__()
for an object are found on its class, so if you want to customize those things for a class, you need the class-of-a-class. A metaclass.printing:
And no, an object can't intercept a request for a stringifying one of its attributes. The object returned for the attribute must define its own
__str__()
behavior.Updated 2023-02-20 for Python 3.x default implementation (python 2 as a comment).
(我知道这是一个旧问题,但是由于所有其他答案都使用元组...)
您可以使用以下简单
classproperty
描述符:使用它:
(I know this is an old question, but since all the other answers use a metaclass...)
You can use the following simple
classproperty
descriptor:Use it like:
首先,您需要创建一个元素,并在其中定义
__ getAttr __()
。第二,不。调用
str(myClass.foo)
indokesmyClass.foo .__ str __()
,因此您需要返回适当的类型myClass.foo
。For the first, you'll need to create a metaclass, and define
__getattr__()
on that.For the second, no. Calling
str(MyClass.Foo)
invokesMyClass.Foo.__str__()
, so you'll need to return an appropriate type forMyClass.Foo
.,没有人指出这个
令人惊讶的是
:(对于python 2.x,更改
myClass
的定义到:)
其他答案对
str
对此解决方案的含义为:必须在实际返回的类型上实现。Surprised no one pointed this one out:
Works:
(for Python 2.x, change definition of
MyClass
to:)
What the other answers say about
str
holds true for this solution: It must be implemented on the type actually returned.根据情况,我使用此模式
,然后您将其导入并使用它。
这避免使用元类,并处理一些用例。
Depending on the case I use this pattern
Then you import and use it.
This avoid use of metaclass, and handle some use cases.