Jaxx
Jaxx

Reputation: 1575

Is __name__ a class level variable?

Normally the class level attributes can be accessed through instance of this class However for attributes like __name__ , __bases__ I cannot access them through an instance. How / where are defined these attributes ? See the code below:

class MyParentClass:
    k = 12

class MyClass(MyParentClass):
    pass

obj = MyClass()

print(MyClass.k)    # ok
print(MyClass.__name__)  # ok
print(obj.k) # ok
print(obj.__name__) # error

Upvotes: 1

Views: 107

Answers (3)

quamrana
quamrana

Reputation: 39354

Perhaps you meant to get the name of the class:

print(obj.__class__.__name__) 

Output:

MyClass

Upvotes: 1

Dan D.
Dan D.

Reputation: 74645

They can not be accessed from the instance because they are not class attributes, but attributes of the class object.

Upvotes: 1

olijeffers0n
olijeffers0n

Reputation: 93

I think the more likely error is the spelling mistake:

print(obj.__name) <---- 

it should have the dunder afterwards

Edit, i see that deceze has commented the same thing

Upvotes: 0

Related Questions