__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):# passprint MyClass.Fooprint MyClass.Barprint str(MyClass)
印刷:
foo!bar!custom str for MyClass
不,对象不能截取对其属性之一进行字符串化的请求。为属性返回的对象必须定义自己的
__str__()行为。



