Python Forum

Full Version: A problem with child class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
class Dog():
	species = 'mammal'
	
	def __init__(self, name, age):
		self.name = name
		self.age = age
		
	def description(self):
		return f'{self.name} is {self.age}'
		
	def speak(self, sound):
		return f'{self.name} says {self.age}'
	
class RussellTerrier(Dog):
	def run(self, speed):
		return f'{self.name} runs {self.speed}'
	
class Bulldog(Dog):
	def run(self, speed):
		return f'{self.name} runs {self.speed}'
	
jim = Bulldog("Jim", 12)
print(jim.description())
	
print(jim.run("slowly"))
Error:
Traceback (most recent call last): File "C:\Python36\kodovi\dogparent.py", line 25, in <module> print(jim.run("slowly")) File "C:\Python36\kodovi\dogparent.py", line 20, in run return f'{self.name} runs {self.speed}' AttributeError: 'Bulldog' object has no attribute 'speed'
I don't understand these errors:
1. Child classes have specific attributes and behaviors as well
2. Bulldog object has 'speed' within method run
You can add the speed at the __init__() or maybe just use it in the run().

def __init__(self, name, age):
        self.name = name
        self.age = age
        self.speed = 'Normal'
Then..

class Bulldog(Dog):
    def run(self, speed):
        self.speed = speed
        return f'{self.name} runs {self.speed}'
Or

class RussellTerrier(Dog):
    def run(self, speed):
        return f'{self.name} runs {speed}'
The speed in the run method is not an attribute of the class, it is a parameter to the method. You would only use self-dot for an attribute, like name. speed you would just reference by itself, like a parameter to a function. This should work:

def run(self, speed):
        return f'{self.name} runs {speed}'