__getattr__()
并且__str__()
对象可以在其类上找到,因此,如果要为类自定义这些内容,则需要一个类。元类。
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