您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

__getattr__用于python中的静态/类变量

__getattr__用于python中的静态/类变量

__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

不,对象不能截取对其属性之一进行字符串化的请求。为属性返回的对象必须定义自己的__str__()行为。

python 2022/1/1 18:42:25 有292人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶