类 and 对象
对象-oriented programming in Python: 类, 实例, 方法, attributes, and __init__.
你将学到
- 定义类 使用类 keyword
- Initialize 对象使用 __init__ and self
- 创建实例方法 and attributes
- Use 类变量 and 静态方法
- 理解 __str__ and __repr__ for 字符串 representation
概念讲解
Defining a Class
class 是一种 blueprint for creating objects. Use the 类 keyword, and follow PEP 8 by using PascalCase for class names:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says Woof!"
The __init__ method is the constructor — it runs when you create a new instance. The self parameter refers to the current instance (like 这个 in other languages) and must be the first parameter of every instance method.
Creating Instances
my_dog = Dog("Rex", 3)
print(my_dog.name) # Rex
print(my_dog.bark()) # Rex says Woof!
your_dog = Dog("Buddy", 5)
print(your_dog.age) # 5
Each instance has its own copy of the instance attributes. my_dog and your_dog are independent objects with their own name and age.
Instance vs Class Variables
class Dog:
species = "Canis familiaris" # class variable — shared by all instances
def __init__(self, name):
self.name = name # instance variable — unique per instance
rex = Dog("Rex")
buddy = Dog("Buddy")
print(rex.species) # Canis familiaris (from class)
print(buddy.species) # Canis familiaris (same class variable)
Class variables are defined on the class itself and shared by all instances. Instance variables are defined in __init__ (with self.) and are unique to each instance. Modifying a class variable through an instance actually creates a new instance variable that shadows it.
Methods
class Calculator:
@staticmethod
def add(a, b):
return a + b
@classmethod
def description(cls):
return f"{cls.__name__} — 简单 calculator"
print(Calculator.add(2, 3)) # 5 — called on the class
print(Calculator.description()) # Calculator — a simple calculator
- Instance methods — take
self, operate on an instance @staticmethod— noselforcls, behaves like a regular function inside the class@classmethod— takescls(the class), often used for alternative constructors
__str__ and __repr__
These "dunder" (double underscore) methods control how your object appears as a string:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
# User-friendly string — used by print() and str()
return f"({self.x}, {self.y})"
def __repr__(self):
# Developer-friendly string — used by repr() and in the REPL
return f"点({self.x!r}, {self.y!r})"
p = Point(3, 4)
print(p) # (3, 4) — uses __str__
print(repr(p)) # Point(3, 4) — uses __repr__
__str__ is for end users; __repr__ is for developers and should ideally be a valid Python expression that could recreate the object. If only __repr__ is defined, it is used as a fallback for __str__.
Properties
Use @属性 to turn a method into a computed attribute:
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
import math
return math.pi * self.radius ** 2
c = Circle(5)
print(c.area) # 78.54... — accessed like an attribute, not a method
Properties let you add computed attributes without changing the interface — callers access c.区域 as if it were a simple attribute, but it is computed on the fly.
示例代码
# A simple class
class Dog:
species = "Canis familiaris" # class variable
def __init__(self, name, age):
self.name = name # instance variables
self.age = age
def bark(self):
return f"{self.name} says Woof!"
def __str__(self):
return f"Dog(name={self.name}, age={self.age})"
# Creating instances
rex = Dog("Rex", 3)
buddy = Dog("Buddy", 5)
print(rex.bark()) # Rex says Woof!
print(rex.species) # Canis familiaris
print(rex) # Dog(name=Rex, age=3)
# Static and class methods
class Calculator:
@staticmethod
def add(a, b):
return a + b
@classmethod
def description(cls):
return f"{cls.__name__} — a simple calculator"
print(Calculator.add(2, 3))
print(Calculator.description())
# Properties for computed attributes
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
import math
return math.pi * self.radius ** 2
@property
def circumference(self):
import math
return 2 * math.pi * self.radius
c = Circle(5)
print(f"Area: {c.area:.2f}") # 78.54
print(f"Circumference: {c.circumference:.2f}") # 31.42
Shows Dog 类使用类/实例变量, __str__, 实例 creation, 静态 and 类方法, and Circle 类使用 @属性 for computed 区域 and circumference.
动手试一试
- JSON Formatter
对象是 经常 serialized 到 JSON — 练习格式化 structured 数据.
- 情况 Converter
类 and 方法 naming 约定 (PascalCase, snake_case).
常见错误
错误写法
Forgetting self as 首先参数的 实例方法
正确做法
每个实例方法必须有 'self' as 它的首先参数. Python 通过实例 automatically — 你做 不包含它 in call. Omitting 它 causes TypeError 关于 missing 实参.
错误写法
定义类 变量那个是 可变 (如列表) and sharing 它们跨越实例
正确做法
可变类 变量是 shared 通过所有实例 — 修改它 in one affects 所有. 定义可变每-实例数据 in __init__ 使用 self. Use 类变量仅 for 不可变 shared constants.
相关资源
相关速查表
- Python Cheatsheet
类定义, 方法, 属性, and dunder 方法.
练习 类 and 对象
8 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。