Python:在实例方法中一般引用类?

时间:2011-09-19 17:26:45

标签: python syntax programming-languages

这个问题很相似,但它与静态方法有关:In Python, how do I reference a class generically in a static way, like PHP's "self" keyword?

如何在实例方法中统一引用类?

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

2 个答案:

答案 0 :(得分:3)

新式类具有self.__class__属性。

在兼容3.x的Python中,所有类都是新式的。

在3.x之前,您使用class a(object):声明它是新式的。

答案 1 :(得分:1)

对于旧式类(如果您的代码是Python 2.x代码,而您的类未继承自object),请使用__class__ property

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

对于新式类(如果您的代码是Python 3代码),请使用type

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

在内部,type使用__class__属性。

相关问题