In Python, an instance is an object created from a class.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} says woof!")
# Create instances
dog1 = Dog("Buddy")
dog2 = Dog("Max")
print(dog1.name) # Buddy
print(dog2.name) # Max
dog1.bark() # Buddy says woof!
In Python, there is no static keyword like in Java or C#, but the equivalent concept is a class variable (sometimes called a static property).
class Student:
school = "ABC School" # class variable
def __init__(self, name):
self.name = name # instance variable
s1 = Student("Alice")
s2 = Student("Bob")
print(s1.school) # ABC School
print(s2.school) # ABC School
A class variable belongs to the class itself. There is only one copy shared by all instances.
An instance variable belongs to a particular object (instance). Each instance has its own copy.
"self" is the conventional variable name to refer to the class instance.
super() is used in inheritance to access methods or attributes from a parent class (superclass).
attribute: a quality or feature of somebody/something
Without super()
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
self.name = name
self.breed = breed
You have to duplicate the initialization logic.
With super()
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
The parent class handles name, and the child class handles breed.
Assuming rover is an instance of a class Dog and speak() is an instance method, this line:
rover.speak()
is equivalent to calling the method through the class and explicitly (明確地) passing the instance as the first argument:
Dog.speak(rover)
In Python, instance methods automatically receive the object (self) as their first parameter. So:
class Dog:
def speak(self):
print("Woof!")
rover = Dog()
rover.speak() # equivalent to:
Dog.speak(rover)
Microsoft Copilot
沒有留言:
發佈留言