【问题标题】:Python keyword to access class variable访问类变量的 Python 关键字
【发布时间】:2014-01-14 10:17:53
【问题描述】:

考虑 Python 3 中的以下类:

class Foo(AnotherClass):
    id_counter = 0
    def __init__(self):
        super().__init__()
        self.id = Foo.id_counter
        Foo.id_counter += 1

是否有一个关键字(在这种情况下类似于 Python 的 super)可用于访问类变量来代替放置类名 Foo

【问题讨论】:

    标签: python python-3.x keyword class-variables


    【解决方案1】:

    type(self)self.__class__ 将返回self 的实际类,它可能是FooFoo 的子类:

    class Foo(AnotherClass):
        id_counter = 0
        def __init__(self):
            super().__init__()
            self.id = type(self).id_counter
            type(self).id_counter += 1
    

    【讨论】:

    • 如果您愿意,也可以使用type(self) 代替self.__class__...毕竟,您会使用len(self) 代替self.__len__(),不是吗? :-P
    • 非常聪明,@mgilson。听起来像是对我的回答!
    • @SimonT -- 在我自己的代码中,我经常使用self.__class__ 主要是因为它在 python2.x 上的行为正常,而您可能正在处理旧式类(哦,太恐怖了!).
    • @mgilson: type() 有时过于直白。type(weakref.proxy(x))weakproxy,而 weakref.proxy(x).__class__x.__class__
    • @eryksun -- 公平点。 instance.__class__ 可写的,所以你不能相信它是 100% 准确的(有时会更好,就像 weakproxy 的情况一样)。
    猜你喜欢
    • 1970-01-01
    • 2012-06-06
    • 2019-10-21
    • 2016-10-11
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多