Khan
Khan

Reputation: 1498

Class variables are unable to perform attribute lookup upon the instance variable

I observed while playing and learning about the vast topic of python OOP, that a a class variable can be accessed by the class instance created, but the class can't call the instance variable defined with the class

class abc():
    height=180
    def __init__(self,name):
        self.age=12 
        self.name=name


ee=abc("Muhammad")
print(ee.height)
print(abc.height)

output

180
180

But if I try to access the class variable directly via the class name, it throes an error.

ee=abc("Muhammad")
print(ee.height)
print(abc.age)

output

AttributeError: class abc has no attribute 'age'

So, I observed this and thought that it would be helpful to share with beginners the depth of python OOP. Please if someone can throw some light on it.

Upvotes: 1

Views: 72

Answers (2)

P. Sai Prasanth
P. Sai Prasanth

Reputation: 48

Every time you define a variable in a class, you either define the variable in the scope of the class or the scope of the instance. The line height = 180, defines height in the class scope(class scope is basically the global scope for the class). The lines self.age = 12 and self.name = name defines age and name in the scope of the instance(instance scope is basically the local scope).

In python if you perform an attribute lookup with an instance(like ee.height), the instance first searches for the variable height in the instance scope, if it isn't found there then the instance searches in the class scope. However, if you perform attribute lookup with a class(like abc.age), the class can't access the local instance scope and hence can search for the variable age only in the class scope. Since there is no variable age in the class scope, it returns an Attribute Error.

Upvotes: 0

timgeb
timgeb

Reputation: 78690

You are not setting an attribute with age = 12 in __init__. All you are doing it do define a local variable that will get garbage collected when __init__ is done.

You'd have to use abc.age = 12 to actually set an attribute on the class abc
(or type(self).age = 12).

I'm assuming this is an educational example, otherwise setting the age in the class for what seems to be modeling persons is not very useful.

Re-setting the class-attribute every time __init__ is called is redundant as well.

Upvotes: 3

Related Questions