+ 3
Can you add attributes to classes that inherit attributes from others?
Eg. If I want to add an attribute 'breed' to dogs, could I do that?
3 Respostas
+ 1
Yes
+ 1
Yes, I read that there are 2 ways to do this. Let's say we want to add 2 attributes "size" and "chaseCat" to Dog class which already inherits "name" and "color" from Animal class:
class Animal:
def __init__(self, name, color):
self.name = name
self.color = color
class Cat(Animal):
def purr(self):
print("Purr...")
class Dog(Animal):
def __init__(self, name, color, size, chaseCat):
Animal.__init__(self, name, color)
# alternative approach:
# super().__init__(name, color)
self.size = size
self.chaseCat = chaseCat
def bark(self):
print ("Woof!")
fido = Dog("Fido", "brown", "big", "likes to chase cats")
print(fido.color)
fido.bark()
print(fido.size)
print(fido.chaseCat)
The result of this code is:
brown
Woof!
big
likes to chase cats
0
yes,derived class have attributes of base class,and can also have its own attributes.