1. Instance variables and class variable basis of Python class
1.1. What are instance variables of classes?
The ** instance variable of a class (Instance Variable) is a variable belonging to a specific instance (object). Each instance has its own independent instance variable and does not interfere with each other.
The instance variable is in__init__
The method is passedself.Variable name
For definition.
Example:
class Person: def __init__(self, name, age): = name # instance variable = age # instance variable p1 = Person("Alice", 25) p2 = Person("Bob", 30) print() # Alice print() # Bob
In the above code,name
andage
is an instance variable, each instance (p1
、p2
) They all have their ownname
andage
, no influence on each other.
1.2. What are class variables?
Class Variable is a variable belonging to the entire class. All instances share the same variable. It is usually defined in the class body, rather than__init__
In the method.
Example:
class Person: species = "Human" # Class variables, all instances share def __init__(self, name): = name # instance variable p1 = Person("Alice") p2 = Person("Bob") print() # Human print() # Human # Modify class variables = "Homo sapiens" print() # Homo sapiens print() # Homo sapiens
Here,species
is a class variable, allPerson
Examples of (p1
, p2
) Share allspecies
Modifying this variable will affect all instances.
1.3. The difference and connection between instance variables of a class and class variables
Comparison items | Instance Variable | Class Variable |
---|---|---|
Define location |
__init__ In the method, useself.Variable name
|
Definition directly within the class body |
Range of action | Only belong to a certain object, each object is independent | Belongs to the entire class, all instances are shared |
Access methods | self.Variable name |
Class name.Variable name orself.Variable name
|
Modification impact | Only affect the current instance, not other instances | Modify class variables to affect all instances |
connect:
- Class variables can be accessed through instances, but if the instance modifies it, it will become an instance variable and will not affect the class itself.
- Instance variables do not affect class variables, each instance has its own independent instance variable.
Example:
class Person: species = "Human" # Class variables def __init__(self, name): = name # instance variable p1 = Person("Alice") p2 = Person("Bob") = "Alien" # Only p1 becomes an instance variable and does not affect class variablesprint() # Alien print() # Human print() # Human
explain:
-
= "Alien"
Actually createdp1
Instance variablesspecies
, will not affectand
。
-
p2
What is still visited is, the value is still
"Human"
。
If you want to modify itspecies
, should be used= "New Value"
。
2. Instance variables and class variables of Python class Comprehensive practical battle
2.1. Common collaboration scenarios for instance variables and class variables of Python classes
In actual development, instance variables and class variables of classes often work together to achieve flexible and efficient data management. The following are several common application scenarios:
Scenario 1: Count all created instances
In some applications, we may want to count the total number of instances of a class, which can be achieved through class variables, while each instance still has its own properties.
Example:
class Person: count = 0 # Class variables, record number of instances def __init__(self, name): = name # instance variable += 1 # For each instance created, count +1 p1 = Person("Alice") p2 = Person("Bob") print() # 2 print() # 2 (Class variables can be accessed through instances)print() # 2
Application scenarios:
- Statistics of users
- Calculate the number of database objects
- Resource Management
Scenario 2: Set the default value
Sometimes, we want all objects to share a default configuration, but at the same time allow the configuration of an instance to be modified separately. At this time, class variables can provide default values, while instance variables can be personalized.
Example:
class Config: default_language = "English" # Class variables, as default language def __init__(self, username, language=None): = username = language if language else Config.default_language # instance variable c1 = Config("Alice") # No language specified, use default valuec2 = Config("Bob", "Spanish") # Custom Language print() # English print() # Spanish
Application scenarios:
- Software global default configuration (language, theme, permissions)
- Device default settings (screen resolution, sound)
Scenario 3: Share immutable objects
If certain properties are the same for all instances and are not modified, using class variables can avoid repeated storage in each instance, saving memory.
Example:
class MathConstants: PI = 3.1415926535 # Class variables E = 2.7182818284 # Class variables # All instances share the same constantprint() # 3.1415926535 print() # 2.7182818284
Application scenarios:
- Physics/Mathematics Constants
- Shared configuration (API URL, database configuration)
Scenario 4: Limit the maximum number of instances
In some cases, we want to control the number of instances of a certain class to prevent too many instances from consuming resources.
Example:
class DatabaseConnection: max_instances = 3 # Class variable, maximum number of instances instances = [] #Storage instances def __new__(cls, *args, **kwargs): if len() >= cls.max_instances: raise Exception("Maximum number of connections") instance = super().__new__(cls) (instance) return instance db1 = DatabaseConnection() db2 = DatabaseConnection() db3 = DatabaseConnection() # db4 = DatabaseConnection() # An exception will be thrown here
Application scenarios:
- Database connection pool
- Thread pool
- Resource Management
2.2. Ideas and techniques for using instance variables and class variables of Python classes in projects
In project development, the rational use of class variables and instance variables can improve the readability, performance and maintenance of the code. Here are some key ideas and tips:
Tips 1: Class variables are used to store "global" information
If a property is the same for all instances and is shared among instances, it should be stored with class variables instead of saving one copy for each instance.
Error example (waste memory):
class Server: def __init__(self): = "localhost" # Save one copy of each instance, wasting space
After optimization (using class variables):
class Server: host = "localhost" # share the same value
Tip 2: Avoid instances accidentally modifying class variables
If you accidentally modify a class variable on an instance, Python will automatically create a new instance variable on the instance, which may lead to unexpected behavior.
Example (Error operation):
class Company: name = "TechCorp" c1 = Company() c2 = Company() = "Startup Inc." # Instance variables are actually created here, and the class variables are not affected. print() # Startup Inc. print() # TechCorp print() # TechCorp
Correct way to do it:
- If you do not want to be modified, you can use class methods to modify the class variables instead of directly modifying them.
class Company: name = "TechCorp" @classmethod def set_name(cls, new_name): = new_name # Modify by class method Company.set_name("NewCorp") print() # NewCorp
Tips 3: Dynamically adjust class variables
In some cases, we may want to dynamically adjust the value of the class variable at runtime, and all instances will automatically adapt to the new value.
Example:
class AppSettings: theme = "Light" @classmethod def change_theme(cls, new_theme): = new_theme # Modify class variables, all instances will be affected s1 = AppSettings() s2 = AppSettings() print() # Light AppSettings.change_theme("Dark") print() # Dark (all instances are affected)
Application scenarios:
- Topic Switch
- Business model adjustment (such as e-commerce promotion model)
Tip 4: Avoid using mutable objects as class variables
If the class variable is a mutable object (such as lists, dictionaries, collections), all instances share the object, which may result in unexpected modifications.
Error example (all instances share the same list):
class Users: user_list = [] # Share list def add_user(self, user): self.user_list.append(user) u1 = Users() u1.add_user("Alice") u2 = Users() u2.add_user("Bob") print(u1.user_list) # ['Alice', 'Bob'] print(u2.user_list) # ['Alice', 'Bob'] (Accidental Sharing)
Solution (using__init__
Let each instance have an independent list):
class Users: def __init__(self): self.user_list = [] # Each instance is independent list def add_user(self, user): self.user_list.append(user) u1 = Users() u1.add_user("Alice") u2 = Users() u2.add_user("Bob") print(u1.user_list) # ['Alice'] print(u2.user_list) # ['Bob']
Summarize
- Class variables are suitable for storing data shared by all instances (such as global configurations, counters).
- Instance variables are suitable for storing independent data for each object (such as user information).
- Avoid instances accidentally modify class variables (if they modify class variables, it is best to use
@classmethod
)。 - Variable objects (lists, dictionaries) should be used as instance variables as possible to prevent data contamination.
These ideas and techniques can help you better manage Python class variables in your project, making the code clearer, more efficient and easier to maintain!
2.3. Instance variables and class variables of Python class What to note in the project
In project development, correctly managing instance variables and class variables of Python classes can improve the readability, performance and maintenance of the code and avoid potential bugs. Here are some key notes covering common pitfalls and best practices.
1. Avoid instance variables overwriting class variables
Problem: When the instance variable and the class variable have the same name, Python will not modify the class variable, but will create a new instance variable on the instance. This can lead to unexpected behavior.
Error example:
class Product: discount = 0.1 # Class variables p1 = Product() p2 = Product() = 0.2 # The class variable is not modified here, but an instance variable of p1 is created. print() # 0.2 (p1 has its own instance variable)print() # 0.1 (p2 still uses class variables)print() # 0.1 (Class variable not changed)
Solution:
- use
@classmethod
Modify the class variable to ensure that all instances share the variable.
class Product: discount = 0.1 # Class variables @classmethod def set_discount(cls, new_discount): = new_discount Product.set_discount(0.2) print() # 0.2
2. Use __slots__ to limit instance variables
Python objects are stored in a dictionary by default (__dict__
) This will result in a large storage overhead for instance variables.
If you want to restrict instance variables of an object, you can use__slots__
, prevents accidental addition of new variables and saves memory.
Example:
class User: __slots__ = ["name", "age"] # Restrict instances to have only these two variables def __init__(self, name, age): = name = age u = User("Alice", 25) = "Female" # AttributeError: 'User' object has no attribute 'gender'
Applicable scenarios:
- Memory optimization (especially when there are a large number of instances)
- Prevent accidental creation of instance variables
3. Avoid bugs caused by variable class variables
If the class variable is a mutable object (such as lists, dictionaries, collections), all instances share the object, which can lead to data contamination.
Error example:
class Team: members = [] # Share list def add_member(self, name): (name) t1 = Team() t1.add_member("Alice") t2 = Team() t2.add_member("Bob") print() # ['Alice', 'Bob'] print() # ['Alice', 'Bob'] (Accidental Sharing)
Solution:__init__
Initialize instance variables in to ensure that each instance has independent data.
class Team: def __init__(self): = [] # Each instance is independent list def add_member(self, name): (name) t1 = Team() t1.add_member("Alice") t2 = Team() t2.add_member("Bob") print() # ['Alice'] print() # ['Bob']
4. Distinguish between class methods and instance methods
In projects, we often need to operate both instance variables and class variables. At this time, we should correctly distinguish the instance methods (self
) and class methods (cls
)。
Example:
class Employee: company = "TechCorp" # Class variables def __init__(self, name): = name # instance variable @classmethod def set_company(cls, new_company): = new_company # Modify class variables def get_info(self): return f"{} works at {}" # Use class method to modify the company nameEmployee.set_company("NewTech") e1 = Employee("Alice") e2 = Employee("Bob") print(e1.get_info()) # Alice works at NewTech print(e2.get_info()) # Bob works at NewTech
Applicable scenarios:
- Instance method is used to obtain/modify instance variables (such as
)。
- Class methods are used to modify class variables (such as
)。
5. Be careful with class variables when inheriting
When a class variable is inherited, the subclass will share the variable of the parent class, but if the subclass modifies it, it may affect all subclass instances.
Error example:
class Parent: shared_list = [] class Child(Parent): pass c1 = Child() c2 = Child() c1.shared_list.append("data") print(c2.shared_list) # ['data'] (Accidental sharing)
Solution: Reinitialize the variable in the subclass:
class Parent: shared_list = [] # Class variables of parent class class Child(Parent): def __init__(self): self.shared_list = [] # Subclass creates its own instance variable c1 = Child() c1.shared_list.append("data") c2 = Child() print(c2.shared_list) # [] (not affected by c1)
6. isinstance detects instance variables, hasattr prevents access to undefined variables
In actual projects, accessing undefined instance variables may causeAttributeError
。
Recommended to usehasattr
Detect whether the variable exists and useisinstance
Check the variable type.
Example:
class User: def __init__(self, name): = name u = User("Alice") print(hasattr(u, "name")) # True print(hasattr(u, "age")) # False
Applicable scenarios:
- avoid
AttributeError
- Dynamic object management
Summarize
Things to note | Problem description | Solution |
---|---|---|
Avoid instance variables overwriting class variables | Modify directlyself.Variable name Probably not really changing the class variable |
use@classmethod Modify class variables |
use__slots__ Limit instance variables |
default__dict__ Storing instance variables and consuming memory |
__slots__ Limit variables |
Variable class variables will be shared by all instances |
list 、dict Sharing may pollute data |
exist__init__ Initialization |
Distinguish between instance methods and class methods | Misuseself orcls May cause errors in modifying scope |
@classmethod Modify class variables, instance method operationself
|
Be careful about class variable sharing when inheriting subclasses | Subclass modification of class variables may affect all subclasses | exist__init__ Redefine in |
usehasattr andisinstance Conduct robustness testing |
Accessing undefined variables will cause an error |
hasattr(instance, 'attr') Testing |
Mastering these skills can make your Python class design more efficient and stable, and avoid unexpected bugs!
3. Comprehensive combat between Python class variables and instance variables
In project development, the rational use of Class Variable and Instance Variable can improve the readability, performance and maintainability of the code. This article will use a complete case to show how to select, use and optimize class variables and instance variables, and at the same time explain in-depth design ideas, best practices, common mistakes and precautions behind them.
Case background
Intelligent logistics management system
Suppose we are developing an intelligent logistics management system to track different express orders and also need to manage company delivery rules.
The core entity involved in the system is an Order, where:
- Each order has a unique order number, recipient, and address (these data belong to the individual order and should be an instance variable).
- All orders share a unified delivery rate and tax rate (these are global settings of the system and should be used with class variables).
- It is necessary to track all created orders and generate a unique ID for each order (class variables are suitable for storage global counters).
Core concept
When developing this system, the following issues need to be clarified:
- When to use class variables? When to use instance variables?
- How to optimize global shared data using class variables?
- How to avoid potential bugs caused by class variables?
Code implementation
class Order: # === Class variable (all orders shared) === delivery_fee = 5.0 # Fixed delivery fee tax_rate = 0.1 # Tax rate (10%) order_count = 0 # Order Counter def __init__(self, recipient, address, base_price): # === Instance variable (each order is independent) === self.order_id = Order.order_count + 1 # Order ID = recipient # recipient = address # Received address self.base_price = base_price # Basic price of goods # Update global order count Order.order_count += 1 def calculate_total(self): """Calculate the total order price (base price + delivery fee + tax)""" tax = self.base_price * Order.tax_rate total_price = self.base_price + Order.delivery_fee + tax return total_price @classmethod def update_delivery_fee(cls, new_fee): """Updated delivery fee""" cls.delivery_fee = new_fee @classmethod def update_tax_rate(cls, new_rate): """Update tax rates""" cls.tax_rate = new_rate @staticmethod def get_system_info(): """Return to system configuration information""" return f"Current delivery fee: {Order.delivery_fee}, Current tax rate: {Order.tax_rate}" # === Test ===order1 = Order("Alice", "New York", 50) order2 = Order("Bob", "San Francisco", 75) print(f"Order1Total price: ${order1.calculate_total()}") print(f"Order2Total price: ${order2.calculate_total()}") # Update delivery feeOrder.update_delivery_fee(8.0) print("After modifying the delivery fee:") print(f"Order1Total price: ${order1.calculate_total()}") print(f"Order2Total price: ${order2.calculate_total()}") # Obtain system informationprint(Order.get_system_info())
Code analysis and thinking reasoning
1. When to select class variables? When to select instance variables?
Variable Type | Applicable scenarios | Application in this case |
---|---|---|
Class variable | Properties that are shared by all instances | Delivery fee (delivery_fee ),tax rate(tax_rate ), order counter (order_count ) |
Instance variable | Properties that are unique to each instance | Order ID (order_id ),recipient(recipient ),address(address ), commodity price (base_price ) |
think:
- For global settings such as delivery fees and tax rates, all orders should follow the same rules, so use class variables.
- For order number, recipient, address and other data, each order is independent, so instance variables are used.
2. How to optimize global data using class variables?
In logistics systems, delivery fees and tax rates are often adjusted, and using class variables can:
- Unified management of delivery fees and tax rates for all orders without modifying the order object one by one.
- when
Order.update_delivery_fee()
When called, all orders will automatically use the new delivery fee.
Example:
Order.update_delivery_fee(8.0) # Modify the global delivery feeprint(Order.get_system_info()) # Now all orders are delivered at 8.0
3. How to avoid potential bugs in class variables?
⚠️ Error example (instance variable accidentally overwrites class variable):
order1.delivery_fee = 10 # It will only affect order1, not Order classprint(order1.delivery_fee) # 10 print(order2.delivery_fee) # 5.0 (not affected)print(Order.delivery_fee) # 5.0 (Class variable has not changed)
🔹 Solution:
- use
@classmethod
Make class variable modifications to ensure that all instances share the same global data.
4. Thinking reasoning: How to optimize order ID?
Order ID requires:
- Each order has a unique number (instance variable).
- A global counter is required to manage unique IDs (class variables).
Implementation method:
self.order_id = Order.order_count + 1 # Order IDOrder.order_count += 1 # Counter increments
In this way, each new order can automatically obtain a unique order number, and all orders share a counter to ensure that the number will not be repeated.
Notes on using class variables and instance variables
✅ 1. Avoid instance variables accidentally overwriting class variables
order1.tax_rate = 0.2 # It will only affect order1 and will not modify the tax_rate of the Order class
Solution:
- Any global data modification should be used
@classmethod
Make modifications, rather than modifying instance variables directly.
✅ 2. Avoid data contamination by variable variables
If the class variable is a mutable object (list, dict), all instances will share the object, which may lead to data contamination.
Error example (multiple instances share the same list):
class Order: items = [] # Shared list (Error) def add_item(self, item): (item) o1 = Order() o2 = Order() o1.add_item("Laptop") print() # ['Laptop'] (Accidental Sharing)
Solution:
- exist
__init__
Initialize instance variables:
class Order: def __init__(self): = [] # A separate list of each instance
Summarize
📌 When to use class variables?
- When variables are applicable to all objects, they do not change depending on the instance, such as global configuration (delivery fee, tax rate).
- When global data is required (order counter).
📌 When to use instance variables?
- When the variable is unique to the instance (order number, recipient, product price).
- When the data needs to be stored independently, it does not affect other instances.
📌 Best Practices
✅ Class variables store global information, and instance variables store individual data. ✅ When modifying class variables, use@classmethod
to ensure sync updates. ✅ Avoid data pollution caused by variable class variables (list, dict).
Through this case, we have mastered how to correctly use Python class variables and instance variables in the project to improve the readability, performance and maintenance of the code!
This is the end of this article about the implementation and difference between Python class variables and instance variables (with examples). For more related contents of Python class variables and instance variables, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!