__getattr__用于python中的静态/类变量 [英] __getattr__ for static/class variables in python
问题描述
我有一个像这样的课程:
I have a class like:
class MyClass:
Foo = 1
Bar = 2
无论何时调用MyClass.Foo
或MyClass.Bar
,我都需要在返回值之前调用一个自定义方法. Python可能吗?我知道创建类的实例并定义自己的__getattr__
方法是可能的.但是我的scnenario涉及这样使用此类而不创建任何实例.
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.
此外,我还需要在调用str(MyClass.Foo)
时调用自定义的__str__
方法. Python提供了这样的选择吗?
Also I need a custom __str__
method to be invoked when str(MyClass.Foo)
is invoked. Does Python provide such an option?
推荐答案
__getattr__()
和__str__()
,因此,如果要为类自定义这些内容,则需要使用以下类:一类的.元类.
__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.
class FooType(type):
def _foo_func(cls):
return 'foo!'
def _bar_func(cls):
return 'bar!'
def __getattr__(cls, key):
if key == 'Foo':
return cls._foo_func()
elif key == 'Bar':
return cls._bar_func()
raise AttributeError(key)
def __str__(cls):
return 'custom str for %s' % (cls.__name__,)
class MyClass:
__metaclass__ = FooType
# in python 3:
# class MyClass(metaclass=FooType):
# pass
print MyClass.Foo
print MyClass.Bar
print str(MyClass)
打印:
foo!
bar!
custom str for MyClass
不,对象不能截取对其属性之一进行字符串化的请求.为该属性返回的对象必须定义自己的__str__()
行为.
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.
这篇关于__getattr__用于python中的静态/类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!