Python Inheritance (OOP)
Page Info
Content
Python Inheritance (OOP)
In Python, inheritance allows a class (child class) to inherit attributes and methods from another class (parent class). This promotes code reuse, modularity, and extensibility in object-oriented programming.
Basic Inheritance Example
# Parent class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
# Child class inherits from Animal
class Dog(Animal):
def speak(self):
print(f"{self.name} barks")
# Create objects
animal = Animal("GenericAnimal")
animal.speak() # Output: GenericAnimal makes a sound
dog = Dog("Buddy")
dog.speak() # Output: Buddy barks
Explanation:
class Dog(Animal):
definesDog
as a subclass ofAnimal
.- The child class inherits all attributes and methods from the parent class.
- Method overriding allows the child class to provide its own implementation of a parent method.
Using super() to Call Parent Methods
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name) # Call parent constructor
self.color = color
def speak(self):
super().speak() # Call parent method
print(f"{self.name} meows")
# Create object
cat = Cat("Whiskers", "Gray")
cat.speak()
# Output:
# Whiskers makes a sound
# Whiskers meows
Key Points
- Inheritance: Child class inherits attributes and methods from parent class.
- Method overriding: Child class can provide a new implementation of a parent method.
- super(): Used to call parent class methods or constructors from the child class.
- Promotes code reuse, modularity, and maintainable OOP design.
SEO Keywords
Python inheritance example, Python OOP inheritance, Python subclass, Python super(), Python method overriding, Python parent child class
Inheritance in Python allows you to create a hierarchy of classes, reuse code efficiently, and extend functionality in a clean and organized way.
Good0 Bad0
댓글목록
등록된 댓글이 없습니다.