Skip to content
← Back to Community
Class inheriting self method
Profile icon
SamKunefeh

Hello everyone, in this code I understand why the error message is popping up, because I am trying to access a class’ attributes by using self, which is only used for instances. However this is simplified from a larger project I am working on, and making the instances would mean changing whole files and how most of the code works. Thus, is there any way I can access the class’ attributes while also using inheritence? Because another object is going to inherit from the Animal class and it IS going to have instances unlike the Bird class.

Voters
Profile icon
SamKunefeh
Comments
hotnewtop
Profile icon
Coder100

Well, the thing is, you are trying to recreate static methods, which is a no no. Make a static method instead and you will see it works.

class Animal: @staticmethod def speak_name(self, text): print(text + self.name) class Bird(Animal): name = "bird" Bird.speak_name("My name is ")

https://codingpointer.com/python-tutorial/static-class-methods

Profile icon
SamKunefeh

@Coder100 Yeah, I did that. But the problem is that staticmethods can neither access class attributes, not instance attributes. So, the decorator would treat self as any other parameter and not the keyword. I think I will just have to bite the bullet and make instances of the Bird class. Nevertheless, thanks for your help!

Profile icon
SamKunefeh
Profile icon
RYANTADIPARTHI

One thing is you haven't made an instance for the class yet. The class should contain the parameter of text so put that in first.

Profile icon
SamKunefeh

@RYANTADIPARTHI Yeah I think I will just have to do that. :)

Profile icon
RYANTADIPARTHI