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
selfis the universally accepted convention for readability.
Example:
class Dog: def __init__(self, name): self.name = name # 'self' points to the new Dog object
self ensures that each Dog object stores its own name.name
Definition: In your class,
nameis 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.nameinside the class, and viaobject.nameoutside.
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.
1. Inheritance
class Dog(Animal):→Doginherits fromAnimal.This means
Dogautomatically gets all attributes and methods defined inAnimalunless overridden.
2. Constructor (__init__)
super().__init__(name)→ calls the parent (Animal) constructor to initializeself.name.self.breed = breed→ adds a new attribute specific toDog.
So each Dog object has both name (from Animal) and breed (added in Dog).
3. Method Overriding
info()inDogoverridesinfo()fromAnimal.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
沒有留言:
發佈留言