ERJAN
ERJAN

Reputation: 24500

can't set attribute in child class from parent

class Human():
    def __init__(self,name):
        print("human's constructor")
        self.name = name


    def sing(self):
        print("la la")

#child class - separate file
from Human import Human
class SuperHuman(Human):

    def __init__(self,name, superpowers = ["super strength", "bulletproof"]):
        print("superhuman's constructor")
        self.name = name # this line gives error
        self.superpowers = superpowers
        super().__init__(name)

This code crashes because in SuperHuman.py the line "self.name = name" - can't set attribute.

if __name__ == '__main__':
    sup = SuperHuman(name="Tick")

    # Instance type checks
    if isinstance(sup, Human):
        print('I am human')
    if type(sup) is SuperHuman:
        print('I am a superhero')

The name field is inherited from Human already, why does not it compile when calling SuperHuman's constructor?

Upvotes: 1

Views: 1184

Answers (2)

ERJAN
ERJAN

Reputation: 24500

for some reason when i changed the "name" field to some random k - the errors disappeared.

This compiles and prints:

class Human:

def __init__(self,k):
    print("human's constructor")
    self.k = k
    print("name assigned: " + str(self.k))

@property
def name(self):
    return self.k

if __name__ == '__main__':
sup = Human("Tick")

# Instance type checks
if isinstance(sup, Human):
    print('I am human')

UPDATE: I found a silly mistake. The method name was ruining it! I should have been more attentive

Upvotes: 0

omu_negru
omu_negru

Reputation: 4770

What is the error you're getting exactly? Best practices dictate that you should call the parent constructor before doing any initialization work, like so

 super(SuperHuman, self).__init__(name)

Then you can drop the self.name = name in the Superhuman constructor, as the parent class takes care of it

Upvotes: 1

Related Questions