Skip to content
Advertisement

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

When I execute this code:

class cls :
    A=1
    def __init__(self):
        self.a=2
        
obj=cls()

print(hasattr(cls,'A'))
print(hasattr(cls,'a'))

print(hasattr(obj,'A'))
print(hasattr(obj,'a'))

I get this output:

True
False
True
True

Everything is clear to me except for the second line. Why do I get False when I execute the hasattr function on the class while I got True when using it with the object for the same attribute?

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement