TypeError when adding variable [closed]

Tags: ,



I took working example code and tried to add another variable self.species = martian under the init method. Seems you cannot do this which doesn’t make sense to me.

# A Sample class with init method 
class Person: 
    
    # init method or constructor 
    def __init__(self, name, species): 
        self.name = name 
        self.species = martian
    
    # Sample Method 
    def say_hi(self, name, species): 
        print('Hello, my name is', self.name)
        print('I am', self.species) 
    
p = Person('Martin')
p.say_hi() 
TypeError: __init__() missing 1 required positional argument: 'species'

Answer

this is how your code should look like.

# A Sample class with init method 
class Person: 
    
    # init method or constructor 
    def __init__(self, name, species): 
        self.name = name 
        self.species = species
    
    # Sample Method 
    def say_hi(self): 
        print('Hello, my name is', self.name)
        print('I am', self.species) 
    
p = Person('Martin', 'martian')
p.say_hi()

I suggest you watch some other beginner’s video lectures on ‘init’ method and ‘Object oriented programming in python’ before writing these type of codes otherwise it would be very hard to understand beyond this point



Source: stackoverflow