You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
dog=Animal("Buddy", "Dog")
cat=Animal("Whiskers", "Cat")
print(dog.make_sound("Woof")) # Buddy the Dog says Woof!print(cat.make_sound("Meow")) # Whiskers the Cat says Meow!
Inheritance
classDog(Animal):
def__init__(self, name, breed):
super().__init__(name, "Dog") # Call the parent constructorself.breed=breed# Additional attributedeffetch(self):
returnf"{self.name} is fetching the ball!"
Using the Subclass
buddy=Dog("Buddy", "Golden Retriever")
print(buddy.make_sound("Woof")) # Buddy the Dog says Woof!print(buddy.fetch()) # Buddy is fetching the ball!
Class vs Instance Variables
classExample:
class_variable="I am shared"def__init__(self, value):
self.instance_variable=value
obj1=Example("Instance 1")
obj2=Example("Instance 2")
print(obj1.class_variable) # I am sharedprint(obj2.class_variable) # I am sharedprint(obj1.instance_variable) # Instance 1print(obj2.instance_variable) # Instance 2
Private and Protected Variables
classPrivateExample:
def__init__(self):
self._protected="I am protected"self.__private="I am private"
obj=PrivateExample()
print(obj._protected) # Accessible but should be treated as private# print(obj.__private) # Will raise an AttributeError