In Python, the key difference is that instance methods operate on a specific object using self, while static methods are independent utility functions inside the class that don’t rely on self or cls. Instance methods are tied to object data, whereas static methods are just grouped logically under the class for organization.
class Dog:
def __init__(self, name):
self.name = name # instance attribute
def speak(self): # instance method
return f"{self.name} says: Bark!"
dog1 = Dog("Rover")
print(dog1.speak()) # Rover says: Bark!
---------
class Dog:
@staticmethod
def bark_sound(): # static method
return "Bark!"
print(Dog.bark_sound()) # Bark!
dog2 = Dog("Buddy")
print(dog2.bark_sound()) # Bark! (works, but doesn’t use dog2)
Microsoft Copilot
沒有留言:
發佈留言