搜尋此網誌

2026年10月7日星期三

Inheritance in Python

In Python, __init__ is a special method inside classes, often called the constructor. It runs automatically whenever you create a new object (instance) from that class. Its main job is to initialize attributes and set up the object’s starting state.

In Python, f'...' refers to an f-string (formatted string literal). It’s a concise way to embed variables or expressions directly inside a string using curly braces {}.

name = "Alice"

age = 25

print(f"My name is {name} and I am {age} years old.")

# Output: My name is Alice and I am 25 years old.

self

  • Definition: A conventional name for the first parameter of instance methods in Python.

  • Property: Refers to the current object instance that the method is being called on.

  • Purpose: Allows access to instance attributes and other methods within the same object.

  • Note: You could technically name it anything, but self is the universally accepted convention for readability.

Example:

class Dog: def __init__(self, name): self.name = name # 'self' points to the new Dog object

Here, self ensures that each Dog object stores its own name.

name

  • Definition: In your class, name is an instance attribute.

  • Property: A variable tied to a specific object, not shared across all objects.

  • Purpose: Stores the dog’s name, unique to each instance.

  • Access: Always referenced through self.name inside the class, and via object.name outside.

Example:

dog1 = Dog("Rover")
dog2 = Dog("Buddy")

print(dog1.name)  # Rover
print(dog2.name)  # Buddy

Each object has its own name value, even though both belong to the same class.


self is the handle to the object itself. name is the data stored inside that object. Together, they let each Dog carry its own identity while sharing the same class blueprint.


Inheritance in Python allows a class (child/subclass) to reuse attributes and methods from another class (parent/superclass), promoting code reusability and enabling method overriding. It’s a cornerstone of object-oriented programming, and in Python it’s implemented simply by listing the parent class in parentheses when defining the child class.

class Animal:
    def __init__(self, name):
        self.name = name
    def info(self):
        print("Animal name:", self.name)

class Dog(Animal):   # Dog inherits from Animal
    def sound(self):
        print(self.name, "barks")

d = Dog("Buddy")
d.info()   # Inherited from Animal
d.sound()  # Defined in Dog

Overriding and Extending

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)   # call parent constructor
        self.breed = breed
    def info(self):
        # override and extend parent method
        super().info()
        print(self.name, "is a", self.breed)

dog = Dog("Buddy", "Golden Retriever")
dog.info()

super() function: Used to call parent methods (commonly in __init__) to ensure proper initialization.

1. Inheritance

  • class Dog(Animal): → Dog inherits from Animal.

  • This means Dog automatically gets all attributes and methods defined in Animal unless overridden.

2. Constructor (__init__)

  • super().__init__(name) → calls the parent (Animal) constructor to initialize self.name.

  • self.breed = breed → adds a new attribute specific to Dog.

So each Dog object has both name (from Animal) and breed (added in Dog).

3. Method Overriding

  • info() in Dog overrides info() from Animal.

  • Inside, it first calls super().info() → runs the parent’s version (prints the name).

  • Then it extends the behavior by printing the breed.


Microsoft Copilot

沒有留言:

發佈留言