Master Python’s Instance, Class, and Static Methods: A Practical Guide
This article explains the differences and uses of instance variables, class variables, instance methods, class methods, and static methods in Python, illustrating each concept with a Dog class example and providing code snippets to help developers write clearer, more maintainable object‑oriented code.
In Python's object‑oriented programming, instance variables, class variables, instance methods, class methods, and static methods each serve distinct purposes for organizing data and behavior.
Instance Variables
Instance variables belong to each object created from a class; they are initialized in __init__ and stored separately for every instance.
class Dog:
def __init__(self, name, color, weight):
self.name = name
self.color = color
self.weight = weightCreating d1 = Dog('大黄', '黄色', 10) and d2 = Dog('旺财', '黑色', 8) gives each dog its own name, color, and weight values.
Class Variables
Class variables are shared across all instances of the class; there is only one copy in memory.
class Dog:
dogbook = {'黄色': 30, '黑色': 20, '白色': 0}
def __init__(self, name, color, weight):
self.name = name
self.color = color
self.weight = weightThe dogbook dictionary can store the count of dogs of each color, and any change to it is reflected in every Dog instance.
Instance Methods
Instance methods receive the instance itself as the first argument ( self) and can access or modify instance variables.
class Dog:
def __init__(self, name, color, weight):
self.name = name
self.color = color
self.weight = weight
def bark(self):
print(f'{self.name}叫了起来')
d1 = Dog('大黄', '黄色', 10)
d1.bark()Class Methods
Class methods are defined with the @classmethod decorator; the first parameter is conventionally named cls and refers to the class itself.
class Dog:
dogbook = {'黄色': 30, '黑色': 20, '白色': 0}
@classmethod
def dog_num(cls):
num = 0
for v in cls.dogbook.values():
num += v
return num
d1 = Dog('大黄', '黄色', 10)
print(f'共有{Dog.dog_num()}条狗')
print(f'共有{d1.dog_num()}条狗') # can also be called via an instanceClass methods are useful for operations that concern the whole class, such as aggregating shared data or providing factory functions.
Static Methods
Static methods are defined with @staticmethod and do not receive self or cls. They behave like regular functions placed inside the class namespace.
class Dog:
@staticmethod
def total_weight(dogs):
total = 0
for dog in dogs:
total += dog.weight
return total
print(f'狗共重{Dog.total_weight([d1, d2])}公斤')Summary
Instance variables store data unique to each object, while class variables provide shared data for the entire class. Instance methods operate on individual objects, class methods manipulate class‑level state, and static methods offer utility functions that are logically related to the class but independent of its state.
Choosing the appropriate method type leads to clearer, more maintainable Python code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
