Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 A problem with child class
#1
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
Quote
#2
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}'
Truman likes this post
Quote
#3
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}'
Truman likes this post
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  can I use 2 child.expect at the same time? korenron 0 94 May-25-2020, 10:41 AM
Last Post: korenron
  calling on a method from one class into another class which is not a child NABA 5 168 Apr-29-2020, 07:49 PM
Last Post: deanhystad
  [split] Python Class Problem astral_travel 12 311 Apr-29-2020, 07:13 PM
Last Post: michael1789
  Python Class Problem JPCrosby 2 264 Apr-28-2020, 06:18 PM
Last Post: buran
  Class problem duckduck23 2 173 Feb-10-2020, 08:52 PM
Last Post: jefsummers
  Class code problem from CS Dojo YouTube Dixon 3 277 Feb-04-2020, 10:23 PM
Last Post: snippsat
  Class Problem scratchmyhead 3 329 Nov-19-2019, 08:28 AM
Last Post: Larz60+
  XML Parsing Child karthi_python 1 363 May-16-2019, 01:37 PM
Last Post: karthi_python
  problem with class method AmirAB 3 629 Feb-13-2019, 01:51 AM
Last Post: AmirAB
  parent/add and child/div PyMan 1 658 Feb-23-2018, 04:38 PM
Last Post: nilamo

Forum Jump:


Users browsing this thread: 1 Guest(s)