[Solved] Why do I get different results when using ‘hasattr’ function on the class and its object for the same attribute? [closed]


Be careful cls is typically used for classmethods for example like this:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def fromBirthYear(cls, name, birthYear):
        return cls(name, date.today().year - birthYear)

So it is better to not use it for your own class names to avoid confusion.

Comming to your question.
In your first block you use a reference to the class itself. So here only static variables are visible as __init__ has not been called.

>>> print(hasattr(cls1,'A'))
True
>>> print(hasattr(cls1,'a'))
False

In the second block you use an instance of the class. Here, __init__() was executed and therefore obj.a exists.

>>> obj=cls1()
>>> print(hasattr(obj,'A'))
True
>>> print(hasattr(obj,'a'))
True

3

solved Why do I get different results when using ‘hasattr’ function on the class and its object for the same attribute? [closed]