Skip to content
Advertisement

Accessing Parent Class Attributes in Child Class as classmethod

I have the following code which works fine :

JavaScript

However, I wish to define the last method – welcome – as a classmethod. So if I do the following change, the code fails.

JavaScript

I get an error as follows :

JavaScript

I realize that Python is looking at the child class – Student for the attributes. However, by inheritance, it should also look at the Parent, where it should find the attributes.

What am I missing here ?

Advertisement

Answer

If method is marked as @classmethod, it has only access to the class and not the instance to the class. Meaning you don’t have access to instance variables. It has nothing to do with inheritance, you cannot even access gradyear attribute in that method. Meaning any variables set in __init__() cannot be access by @classmethod. You can read more about @classmethod here.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement