开发者

Python: Reference to a class generically in an instance method?

This question is similar, but it pertains to static methods: In Python, how do I reference a class generically in a static way, like PHP's "开发者_如何学Pythonself" keyword?

How do you refer to a class generically in an instance method?

e.g.

#!/usr/bin/python
class a:
    b = 'c'
    def __init__(self):
        print(a.b) # <--- not generic because you explicitly refer to 'a'

    @classmethod
    def instance_method(cls):
        print(cls.b) # <--- generic, but not an instance method


For old-style classes (if your code is Python 2.x code, and your class in not inheriting from object), use the __class__ property.

def __init__(self):
    print(self.__class__.b) # Python 2.x and old-style class

For new-style classes (if your code is Python 3 code), use type:

def __init__(self):
    print(self.__class__.b) # __class__ works for a new-style class, too
    print(type(self).b)

Internally, type uses the __class__ property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜