1. Basic Concepts of Classes and Objects
Python is a language that supports object-oriented programming. Object-oriented programming (OOP) organizes programs through classes and objects, combining data with the behavior that operates on that data.
To understand classes and objects, you first need to grasp two concepts:
- Class: describes what attributes and behaviors a category of objects has; it is essentially the definition of an object.
- Object: a concrete instance created from a class; it has its own state and can perform the behaviors defined by the class.
For example, in a student management system, you can define a Student class to describe students' attributes such as name, age, and student ID, as well as behaviors such as studying and introducing themselves.
Different students are all instances of the Student class, but each student can have different attribute values.
class Student:
pass
student1 = Student()
student2 = Student()
print(type(student1))
print(type(student2))
print(student1 is student2)
Output:
<class '__main__.Student'>
<class '__main__.Student'>
False
Here:
Studentis a class.student1andstudent2are two independent objects.- The two objects are of the same type, but they are not the same object.
1. The Relationship Between Classes and Objects
A single class can create multiple objects, and each object has the basic structure defined by that class.
flowchart TD
A["Student Class"] --> B["student1 instance"]
A --> C["student2 instance"]
A --> D["student3 instance"]
B --> E["Name: Alice"]
C --> F["Name: Bob"]
D --> G["Name: Charlie"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#F6FAF7,stroke:#DCE9E0,color:#334155
style F fill:#F6FAF7,stroke:#DCE9E0,color:#334155
style G fill:#F6FAF7,stroke:#DCE9E0,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note that a class is not a simple copy template of an object in memory. In Python, a class is itself an object, and it can be assigned, passed around, and modified dynamically.
2. Core Differences Between Classes and Objects
| Comparison Dimension | Class | Object |
|---|---|---|
| Essence | A type definition | An instance of a class |
| Role | Describes attributes and behaviors | Stores concrete state and performs behaviors |
| How it is created | Defined using class |
Created by calling a class |
| Quantity | One class can create multiple instances | Each instantiation can produce a new object |
| Attributes | Can define class attributes and methods | Can have instance attributes |
| Example | Student |
An instance created by Student() |
2. Defining Classes with class
Python uses the class keyword to define a class.
Basic syntax:
class ClassName:
"""Class docstring"""
# Class attribute
attribute = value
# Method
def method(self):
pass
For example:
class Student:
"""Student class"""
school = "Python Academy"
def study(self):
print("学生正在学习")
Here a Student class is defined.
Among them:
classis the keyword for defining a class.Studentis the class name.schoolis a class attribute.study()is an instance method.selfrefers to the instance on which the method is called.
1. Class Naming Conventions
Python class names usually use upper camel case, also known as PascalCase.
class Student:
pass
class BankAccount:
pass
class ShoppingCart:
pass
class UserProfile:
pass
Recommended:
- Use names with business meaning.
- Class names are usually nouns.
- Capitalize the first letter of each word.
- Avoid names that are too broad or ambiguous.
Not recommended:
class student_info:
pass
class doSomething:
pass
class A:
pass
2. A Class Definition Is Itself Executable Code
In Python, a class definition is not merely a declaration.
When the class statement is executed, Python executes the code in the class body and uses the execution results to construct the class object.
class Example:
print("正在执行类定义")
value = 100
def show(self):
print(self.value)
When the code is executed:
正在执行类定义
This output occurs during the class definition phase, not when an instance is created.
Only after the class definition finishes executing is the name Example bound to the created class object.
III. Creating Objects and Instantiation
After defining a class, you can create objects by calling the class. This process is called instantiation.
class Student:
pass
student = Student()
print(student)
print(type(student))
Output is similar to:
<__main__.Student object at 0x...>
<class '__main__.Student'>
Student() is an instantiation operation.
1. Creating Multiple Objects from One Class
class Student:
pass
student1 = Student()
student2 = Student()
student3 = Student()
print(student1 is student2)
print(student2 is student3)
Output:
False
False
Each call to an ordinary class construction expression usually creates a new instance.
However, if a class overrides __new__(), special behaviors such as instance reuse can also be implemented, so you cannot absolutely assume that every call necessarily produces a completely new object.
2. Using isinstance() to Determine Object Type
Python provides isinstance() to determine whether an object belongs to a specified type or its subclass.
class Student:
pass
student = Student()
print(isinstance(student, Student))
print(isinstance(student, object))
print(isinstance(student, str))
Output:
True
True
False
Because ordinary classes in Python inherit from object by default, an instance of Student is also an instance of object.
3. Using type() to Inspect Object Type
class Student:
pass
student = Student()
print(type(student))
print(type(student) is Student)
Output:
<class '__main__.Student'>
True
type() can obtain the actual type of an object.
type(obj) is SomeClass only checks whether the object's direct type is exactly the specified class; unlike isinstance(), it does not treat subclass instances as matching.
For example:
class Animal:
pass
class Dog(Animal):
pass
dog = Dog()
print(type(dog) is Animal)
print(isinstance(dog, Animal))
Output:
False
True
In engineering practice, when determining whether an object belongs to a certain type hierarchy, isinstance() is usually the first choice.
IV. Attributes of Objects
An attribute is a name and value associated with an object or class, used to describe the object's state or provide information related to the object.
Common attributes in Python include:
- Instance attributes.
- Class attributes.
- Dynamically added attributes.
- Special attributes.
1. Instance Attributes
Instance attributes belong to a specific object, and different objects can hold different instance attribute values.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student1 = Student("Alice", 20)
student2 = Student("Bob", 22)
print(student1.name)
print(student1.age)
print(student2.name)
print(student2.age)
Output:
Alice
20
Bob
22
Here:
self.name = name
self.age = age
means binding the passed-in parameters as attributes of the current instance.
The two instances each have their own name and age.
2. Class Attributes
Class attributes are defined in the class namespace and are usually used to hold information shared by all instances of that class.
class Student:
school = "Python Academy"
def __init__(self, name):
self.name = name
student1 = Student("Alice")
student2 = Student("Bob")
print(Student.school)
print(student1.school)
print(student2.school)
Output:
Python Academy
Python Academy
Python Academy
Class attributes can be accessed through the class name or through an instance.
3. Differences Between Instance Attributes and Class Attributes
class Student:
school = "Python Academy"
def __init__(self, name):
self.name = name
student = Student("Alice")
print(student.__dict__)
print(Student.__dict__)
student.__dict__ usually holds the instance's own attributes.
Student.__dict__ is the class's namespace mapping, containing information such as the attributes and methods defined in the class.
The two are not the same namespace.
| Comparison Dimension | Instance Attributes | Class Attributes |
|---|---|---|
| Definition Location | Usually assigned via self in an instance method |
In the class definition body |
| Owning Object | A specific instance | The class object |
| Data Characteristics | Can differ for each instance | Usually accessed and shared by instances |
| Access Method | Instance | Class or instance |
| Typical Uses | Name, age, order status | Shared configuration, default values, statistics |
4. Instance Attributes Override Class Attributes
When an instance and its class have attributes with the same name, ordinary instance attribute reads usually give priority to the instance's own attribute.
class Student:
school = "Python Academy"
student1 = Student()
student2 = Student()
print(student1.school)
student1.school = "AI Academy"
print(student1.school)
print(student2.school)
print(Student.school)
Output:
Python Academy
AI Academy
Python Academy
Python Academy
Executing:
student1.school = "AI Academy"
usually only creates an attribute with the same name in the instance namespace of student1; it does not modify the class attribute.
5. Dynamically Adding Attributes
Python objects generally allow instance attributes to be added dynamically at runtime.
class User:
pass
user = User()
user.name = "Alice"
user.age = 25
user.email = "alice@example.com"
print(user.name)
print(user.age)
print(user.email)
This reflects the dynamic nature of Python's object model.
However, not all objects allow arbitrary attributes to be added. For example, classes that use __slots__ to restrict their attribute space, as well as some built-in objects, may not support this operation.
5. Object Methods
A method is a function defined in a class that describes behavior that an object or class can perform.
Common types of methods in Python include:
- Instance methods.
- Class methods.
- Static methods.
1. Instance Methods
Instance methods usually take self as their first parameter and are used to access the attributes and other methods of the current instance.
class Student:
def __init__(self, name):
self.name = name
def introduce(self):
print(f"大家好,我叫 {self.name}")
student = Student("Alice")
student.introduce()
Output:
大家好,我叫 Alice
Calling:
student.introduce()
This can be understood as:
Student.introduce(student)
When a normal function attribute is accessed through an instance, Python binds the function descriptor to the instance, forming a bound method.
2. Class Methods
Class methods are defined using the @classmethod decorator; their first parameter is usually cls, which represents the class to which they are bound.
class Student:
school = "Python Academy"
@classmethod
def get_school(cls):
return cls.school
print(Student.get_school())
Output:
Python Academy
Class methods are typically used to operate on class-level data and can also be used to create objects.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_string(cls, text):
name, age = text.split(",")
return cls(name, int(age))
student = Student.from_string("Alice,20")
print(student.name)
print(student.age)
Creating instances with cls allows a subclass that inherits this alternative constructor to still create instances of the corresponding subclass.
3. Static Methods
Static methods are defined using the @staticmethod decorator and do not automatically receive self or cls.
class MathUtils:
@staticmethod
def add(a, b):
return a + b
print(MathUtils.add(10, 20))
Output:
30
Static methods are suitable for organizing utility functions that logically belong to a class but do not need to access instance state or class state.
4. Differences Among the Three Types of Methods
| Method Type | Decorator | First Parameter | Main Purpose |
|---|---|---|---|
| Instance method | None | self |
Operate on instance state |
| Class method | @classmethod |
cls |
Operate on class state; alternative constructor |
| Static method | @staticmethod |
No special requirement | Organize related utility logic |
6. The Roles of self and cls
Neither self nor cls is a Python keyword; they are conventional parameter names.
They are used to represent the current instance in instance methods and the current class in class methods, respectively.
1. self Represents the Current Instance
class User:
def __init__(self, name):
self.name = name
def show(self):
print(self.name)
user1 = User("Alice")
user2 = User("Bob")
user1.show()
user2.show()
Output:
Alice
Bob
When two instances call the same method, the self passed in points to a different instance each time.
2. cls represents the currently bound class
class Animal:
category = "动物"
@classmethod
def get_category(cls):
return cls.category
class Dog(Animal):
category = "犬科"
print(Animal.get_category())
print(Dog.get_category())
Output:
Animal
Canine
When a subclass calls an inherited class method, cls is bound to the subclass, so it can read the class attribute overridden by the subclass.
3. Differences between self and cls
flowchart TD
A["Method call"] --> B{"Method type"}
B --> C["Instance method"]
B --> D["Class method"]
B --> E["Static method"]
C --> F["self is bound to the instance"]
D --> G["cls is bound to the class"]
E --> H["No automatically bound parameter"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
VII. Object Initialization and Creation Mechanism
When creating an object, Python does more than allocate a block of memory; it also executes the corresponding instance creation and initialization logic.
This involves two special methods:
__new__(): creates and returns the instance.__init__(): initializes an already created instance.
1. init() initialization method
__init__() is the most commonly used initialization method in Python.
class User:
def __init__(self, username, age):
self.username = username
self.age = age
user = User("Alice", 25)
print(user.username)
print(user.age)
Execution:
user = User("Alice", 25)
Python first creates the instance, then calls the corresponding initialization method.
__init__() must return None and cannot return any other object.
2. new() instance creation method
__new__() is the special method responsible for creating instances.
class User:
def __new__(cls, *args, **kwargs):
print("创建实例")
instance = super().__new__(cls)
return instance
def __init__(self, name):
print("初始化实例")
self.name = name
user = User("Alice")
Output:
Creating instance
Initializing instance
Where:
clsrepresents the class for which an instance needs to be created.super().__new__(cls)calls the parent class's instance creation logic.return instancereturns the created object.
If the object returned by __new__() is not an instance of the current class or one of its subclasses, the current class's __init__() will usually not be executed.
3. Object Creation Flow
flowchart TD
A["Call class to create object"] --> B["Execute __new__"]
B --> C["Allocate and return instance"]
C --> D{"Returned object belongs to the target class or a subclass"}
D -->|Yes| E["Execute __init__"]
D -->|No| F["Skip current class initialization"]
E --> G["Get initialized instance"]
F --> H["Return result of __new__"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
4. Differences Between new() and init()
| Comparison Dimension | __new__() |
__init__() |
|---|---|---|
| Main responsibility | Create instance | Initialize instance |
| First parameter | cls |
self |
| Execution timing | Before initialization | After instance creation |
| Return value | Return the instance object | Must return None |
| Common use cases | Special object creation, customizing immutable types | Set instance attributes |
In day-to-day development, most business classes only need to define __init__().
8. Accessing and Managing Object Attributes
Python provides multiple ways to access, modify, inspect, and delete object attributes.
1. Accessing Attributes with Dot Notation
class User:
def __init__(self, name):
self.name = name
user = User("Alice")
print(user.name)
user.name = "Bob"
print(user.name)
Output:
Alice
Bob
Dot notation is the most common way to operate on attributes.
2. Getting Attributes with getattr()
getattr() can dynamically get an attribute based on an attribute name string.
class User:
def __init__(self):
self.name = "Alice"
user = User()
print(getattr(user, "name"))
print(getattr(user, "age", 18))
Output:
Alice
18
If the attribute does not exist and no default value is provided, getattr() will raise AttributeError.
3. Setting Attributes with setattr()
class User:
pass
user = User()
setattr(user, "name", "Alice")
setattr(user, "age", 25)
print(user.name)
print(user.age)
setattr() is suitable for scenarios where the attribute name needs to be determined dynamically.
4. Checking Attributes with hasattr()
class User:
name = "Alice"
user = User()
print(hasattr(user, "name"))
print(hasattr(user, "age"))
Output:
True
False
hasattr() attempts to get the specified attribute and returns a Boolean result depending on whether AttributeError occurs.
5. Deleting Attributes with delattr()
class User:
def __init__(self, name):
self.name = name
user = User("Alice")
delattr(user, "name")
print(hasattr(user, "name"))
Output:
False
After an instance attribute is deleted, if an attribute with the same name exists on the class, subsequent access may still find the class attribute.
6. Common Attribute Operation Functions
| Function | Purpose | Example |
|---|---|---|
getattr() |
Get an attribute | getattr(obj, "name") |
setattr() |
Set an attribute | setattr(obj, "name", "Alice") |
hasattr() |
Check for an attribute | hasattr(obj, "name") |
delattr() |
Delete an attribute | delattr(obj, "name") |
vars() |
Get the object's __dict__ |
vars(obj) |
dir() |
View the names of the object's visible attributes | dir(obj) |
Note that vars(obj) does not work for all objects. If an object has no __dict__, calling it may raise a TypeError.
IX. Object Identity, Type, and Value
Every object in Python can be understood from three aspects: identity, type, and value.
1. Object Identity
Object identity is used to distinguish different objects.
You can use id() to obtain an object's identity.
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(id(a))
print(id(b))
print(id(c))
print(a is b)
print(a is c)
Output is similar to:
140000000000000
140000000000128
140000000000000
False
True
The exact numbers depend on the runtime environment.
2. Object Type
An object's type determines which operations it supports and how its behavior is interpreted.
number = 100
text = "Python"
items = [1, 2, 3]
print(type(number))
print(type(text))
print(type(items))
Output:
<class 'int'>
<class 'str'>
<class 'list'>
3. Object Value
An object's value is the data content that the object represents.
number = 100
print(number)
print(number + 50)
Output:
100
150
4. The Relationship Between Identity, Type, and Value
| Concept | Meaning | Common Operations |
|---|---|---|
| Identity | Distinguishes objects | id(), is |
| Type | The type the object belongs to | type(), isinstance() |
| Value | The content the object represents | Direct access or performing operations |
For example:
a = [1, 2]
b = [1, 2]
c = a
print(a == b)
print(a is b)
print(a is c)
Output:
True
False
True
== is generally used to compare whether the values of objects are equal.
is is used to determine whether two names reference the same object.
These two operations must not be confused.
X. Python Classes Are Also Objects
In Python, classes themselves are also objects.
Ordinary classes are usually created by the metaclass type.
class Student:
pass
print(type(Student))
print(type(Student()))
print(isinstance(Student, object))
Output:
<class 'type'>
<class '__main__.Student'>
True
Here: