1. What Are Classes and Objects
Classes and objects are the foundational concepts of object-oriented programming (OOP).
They represent two different levels:
- Class: An abstract description of the common characteristics and behaviors of a category of things, defining which attributes and methods an object should have.
- Object: A concrete instance of a class, possessing actual data and able to perform the behaviors defined by the class.
For example, in a user management system:
Useris a class used to describe which attributes and behaviors a user has.- Zhang San and Li Si are two different user objects, each with independent user data.
A class describes the common structure, while objects carry concrete state.
2. Basic Composition of a Class
A class is usually composed of the following parts:
| Component | Description | Example |
|---|---|---|
| Class name | Identifies the name of the class | User |
| Attribute | Describes the data characteristics of an object | name, age |
| Method | Describes the behaviors an object can perform | login(), logout() |
| Constructor | Executes initialization logic when creating an object | __init__(), constructor() |
| Access control | Restricts the access scope of attributes and methods | public, private |
Note that not all programming languages implement classes in exactly the same way. For example, Python's attribute access control mainly relies on naming conventions and name mangling, while Java provides explicit access modifiers.
2.1 Attributes
Attributes are used to describe the state of an object.
For example, a user object may have:
User
├── id
├── name
├── age
├── email
└── status
Attributes can be further divided into:
- Instance attributes: Belong to a specific object; different objects usually have their own independent values.
- Class attributes: Belong to the class itself and are usually shared by multiple instances of that class.
- Static attributes: In some languages, used to represent members that are unrelated to a specific instance and belong to the class or type; the exact semantics depend on the language.
- Computed attributes: Attributes obtained dynamically through computation or accessors, not necessarily stored directly as independent fields.
Take Python as an example:
class User:
system_name = "Reverie" # class attribute
def __init__(self, name, age):
self.name = name # instance attribute
self.age = age # instance attribute
Create two objects:
user1 = User("Alice", 25)
user2 = User("Bob", 30)
print(user1.name) # Alice
print(user2.name) # Bob
print(user1.system_name) # Reverie
print(user2.system_name) # Reverie
Here:
nameandageare stored separately in the attribute storage of different instances.system_nameis defined on the class, and both objects can access it through attribute lookup.
Note that a Python instance can create an instance attribute with the same name through assignment, thereby shadowing the class attribute:
user1.system_name = "Custom"
print(user1.system_name) # Custom
print(user2.system_name) # Reverie
print(User.system_name) # Reverie
Therefore, a class attribute does not mean that an instance absolutely cannot have an attribute with the same name.
2.2 Methods
Methods are behavioral logic defined in a class, used to operate on object data or perform specific tasks.
For example:
class User:
def __init__(self, name):
self.name = name
self.logged_in = False
def login(self):
self.logged_in = True
print(f"{self.name} 登录成功")
def logout(self):
self.logged_in = False
print(f"{self.name} 已退出")
Methods can be divided into:
| Method type | Purpose | Python example |
|---|---|---|
| Instance method | Operates on the data of a specific instance | def login(self) |
| Class method | Operates on class-level data or behavior | @classmethod |
| Static method | Provides helper behavior not directly tied to instance state | @staticmethod |
Different languages have different rules for defining and calling methods. For example, Java uses static to declare static methods, while C++ uses static member functions.
2.3 Constructor
A constructor is used for initialization during object creation.
The construction mechanisms differ from language to language:
| Language | Common construction mechanism |
|---|---|
| Python | __init__() |
| Java | A constructor with the same name as the class |
| C++ | A constructor function with the same name as the class |
| JavaScript | constructor() |
| Go | Typically uses factory functions or constructor conventions |
| Rust | Typically uses associated functions such as new() |
Take Java as an example:
public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
}
Create an object:
User user = new User("Alice", 25);
Here, two concepts need to be distinguished:
- Object creation: establishing the runtime representation of an object and acquiring the resources it needs.
- Object initialization: setting the initial state of an object's attributes so that it satisfies the expected constraints.
In different languages, these two steps may be handled by different mechanisms.
For example, in Python, __new__() is responsible for creating and returning an instance, while __init__() is responsible for initializing the instance that has already been created.
III. The Relationship Between Classes and Objects
The relationship between a class and an object is one of template and instance.
A single class can create multiple objects, and each object can have its own independent instance state.
flowchart TB
A["User class"]
B["user1 object"]
C["user2 object"]
D["user3 object"]
A --> B
A --> C
A --> D
B --> E["name: Alice<br/>age: 25"]
C --> F["name: Bob<br/>age: 30"]
D --> G["name: Carol<br/>age: 28"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
A few points should be made clear:
- A class can usually create multiple instances.
- Different instances can share the same attribute structure, but their attribute values can differ.
- Instance methods can usually access and modify the state of the current instance.
- A class definition itself is not equivalent to any particular object.
- The relationship between classes and objects does not mean that all languages use the same memory layout and instantiation mechanisms.
IV. Object Creation and Instantiation
Instantiation is the process of creating a concrete object from a class definition.
Take Python as an example:
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def get_price(self):
return self.price
product = Product("Keyboard", 299)
print(product.name)
print(product.get_price())
The object creation process can be abstracted as:
flowchart TB
A["Define class Product"]
B["Call the class to create an object"]
C["Allocate resources required by the object"]
D["Create object instance"]
E["Execute initialization logic"]
F["Obtain usable object"]
G["Access properties and call methods"]
A --> B
B --> C
C --> D
D --> E
E --> F
F --> G
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
This is a conceptual abstraction of the process and does not mean that all languages strictly follow these independent steps.
For example:
- Java uses
newto create an object and executes the constructor. - C++ can create objects on the stack or in dynamic storage.
- Python creates instances by calling the class object.
- JavaScript uses
newto call a constructor, and can also create objects directly through object literals. - Go usually creates struct instances through composite literals or
new.
5. Three Core Characteristics of Objects
In object-oriented theory, objects usually have three important characteristics:
5.1 State
State describes an object's data at a given moment.
For example:
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
The state of the account object can be represented as:
owner = Alice
balance = 1000
When the balance changes, the object's state changes accordingly.
account.balance -= 200
The new state is:
owner = Alice
balance = 800
5.2 Behavior
Behavior represents the operations that an object can perform.
For example:
class Account:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("余额不足")
self.balance -= amount
deposit() and withdraw() are behaviors of the account object.
Objects not only store data but can also maintain their own state through methods.
5.3 Identity
Identity is used to distinguish different objects.
Two objects may be different objects even if their attribute values are exactly the same.
user1 = User("Alice", 25)
user2 = User("Alice", 25)
print(user1 == user2)
print(user1 is user2)
Without a custom __eq__(), ordinary Python objects use identity semantics for equality by default, so the two expressions above usually produce the following respectively:
False
False
If __eq__() is customized, == can compare object contents according to business rules, while is is still used to determine whether two references point to the same object.
This reveals three concepts that are easily confused:
| Concept | Meaning |
|---|---|
| Identity | Whether the objects are the same entity |
| Equality | Whether the contents or business meanings of two objects are equal |
| State | The data currently stored by the object |
When designing business systems, it is necessary to clarify whether to judge object identity or object value.
For example, two user objects with the same name and age do not necessarily correspond to the same user record in the database.
6. Object References and Memory Model
Objects are usually not simple variable values, but entities created at runtime.
A variable in a program may store the object itself, or it may store a reference or handle to the object, depending on the language implementation.
Take Python as an example:
user1 = User("Alice", 25)
user2 = user1
user2.name = "Bob"
print(user1.name) # Bob
print(user2.name) # Bob
Here user1 and user2 point to the same object.
flowchart TB
A["Variable user1"]
B["Variable user2"]
C["The same User object"]
D["name: Bob"]
E["age: 25"]
A --> C
B --> C
C --> D
C --> E
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Therefore, modifying the object through any one reference may affect the results observed through other references.
6.1 Reference assignment is not the same as object copying
This is a very important concept in object-oriented programming.
user1 = User("Alice", 25)
user2 = user1
The above code does not create a second User object; instead, it makes two variables reference the same instance.
If you need to create an independent object, you need to perform a copy operation.
import copy
user1 = User("Alice", 25)
user2 = copy.copy(user1)
user2.name = "Bob"
print(user1.name) # Alice
print(user2.name) # Bob
However, a shallow copy only copies the outer object, and nested objects inside may still share references.
class Team:
def __init__(self, members):
self.members = members
team1 = Team(["Alice", "Bob"])
team2 = copy.copy(team1)
team2.members.append("Carol")
print(team1.members)
print(team2.members)
The members attributes of the two objects reference the same list, so modifying the list of one object also affects the other object.
If you need to recursively copy nested objects, you can consider a deep copy, but deep copying may also be affected by circular references, custom copy logic, and non-copyable resources.
6.2 Are objects necessarily stored in heap memory?
Not necessarily.
Although many object-oriented languages allocate objects in heap memory, this cannot be regarded as a universal rule for all languages and all implementations.
For example:
- Ordinary Java objects are usually managed by the JVM and are allocated on the heap in common implementations.
- Python objects are usually managed by the runtime; in CPython, most objects are managed through dynamic memory allocation mechanisms.
- C++ objects can have automatic, static, or dynamic storage duration.
- The storage location of a Rust object depends on its ownership, lifetime, and specific usage.
- Compilers may also eliminate actual heap allocation through optimizations such as escape analysis and scalar replacement.
Therefore, classes and objects are abstractions at the language level and cannot be directly equated with any one fixed memory layout.
7. The Difference Between Class Attributes and Instance Attributes
Class attributes and instance attributes are two concepts that are easily confused in practical development.
| Comparison aspect | Class attribute | Instance attribute |
|---|---|---|
| Ownership | Class | Specific instance |
| Definition location | Inside the class definition | Usually created during instance initialization or runtime |
| Data sharing | Usually shared and accessed by instances | Each instance can hold its own independently |
| Impact of modification | Depends on the language and attribute lookup rules | Usually affects only the current instance |
| Common uses | Configuration, constants, shared counters | User information, order status, business data |
Python example:
class User:
user_count = 0
def __init__(self, name):
self.name = name
User.user_count += 1
user1 = User("Alice")
user2 = User("Bob")
print(User.user_count) # 2
Here user_count records the number of user instances created.
However, note that class attributes are not inherently thread-safe. If multiple threads modify shared state at the same time, synchronization mechanisms need to be considered.