+ 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?

19th Jul 2016, 6:54 AM
Vladimir K. Bobyr
Vladimir K. Bobyr - avatar
3 ответов
+ 1
Yes
21st Jul 2016, 8:33 AM
DIMITRIOS TSORTANIDIS
DIMITRIOS TSORTANIDIS - avatar
+ 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
23rd Jul 2016, 12:55 PM
Trang Hoang
Trang Hoang - avatar
0
yes,derived class have attributes of base class,and can also have its own attributes.
21st Jul 2016, 2:54 PM
Jyoti Sheokand
Jyoti Sheokand - avatar