Search code examples
pythonsyntaxprogramming-languages

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 "self" 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

Solution

  • 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.