Python 类和对象
一、类定义
1. 成员变量
(1)实例变量
实例变量属于对象本身,定义在 __init__ 方法中,通过 self 进行绑定,每个对象各自独立,互不影响。
class Person:
def __init__(self, name, age):
self.name = name # 实例变量
self.age = age
p1 = Person("Alice", 20)
p2 = Person("Bob", 22)
print(p1.name, p2.name)
(2)类变量
类变量属于类本身,定义在类中、方法外,所有对象共享同一份数据,通常用于统计或共享状态。
class Person:
species = "Human" # 类变量
def __init__(self, name):
self.name = name
print(Person.species)
2. 成员方法
(1)实例方法
实例方法的第一个参数是 self,用于访问实例变量和其他实例方法。
class Dog:
def bark(self):
print("汪汪!")
dog = Dog()
dog.bark()
(2)类方法
类方法使用 @classmethod 装饰,第一个参数为 cls,常用于操作类变量或创建对象。
class User:
count = 0
def __init__(self):
User.count += 1
@classmethod
def get_count(cls):
return cls.count
(3)静态方法
静态方法使用 @staticmethod 装饰,与类相关,但不依赖对象或类变量。
class MathUtil:
@staticmethod
def add(a, b):
return a + b
3. self 的作用
self 指向当前对象实例,用于区分实例变量和局部变量,确保不同对象之间的数据独立。
class Counter:
def __init__(self, value):
self.value = value
def increase(self):
self.value += 1
c1 = Counter(1)
c2 = Counter(10)
c1.increase()
c2.increase()
print(c1.value, c2.value)
二、类构造方法
构造方法 __init__ 在对象创建时自动执行,主要用于初始化实例变量,可设置默认参数。
class Student:
def __init__(self, name, score=60):
self.name = name
self.score = score
stu = Student("Tom", 90)
print(stu.name, stu.score)
三、类常用魔术方法
1. 对象字符串表示
__str__ 用于 print() 输出。
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return f"书名:{self.title}"
print(Book("Python"))
2. 运算符重载
通过重写魔术方法实现运算符功能,例如 + 对应 __add__。
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
v = Vector(1, 2) + Vector(3, 4)
print(v.x, v.y)
3. 容器相关魔术方法
实现 __len__、__getitem__ 等方法后,对象可像容器一样使用。
class MyList:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, index):
return self.data[index]
ml = MyList([1, 2, 3])
print(len(ml), ml[0])
4. 其他常用魔术方法
(1)对象创建与销毁
__new__(cls):创建对象(较少直接使用)__init__(self):初始化对象__del__(self):对象销毁时调用(不推荐依赖)
(2)对象字符串表示
__str__(self):print()/str()调用__repr__(self):调试和解释器输出
(3)运算符重载
__add__(self, other):加法+__sub__(self, other):减法-__mul__(self, other):乘法*__eq__(self, other):等于==__lt__(self, other):小于<__le__(self, other):小于等于<=
(4)容器相关
__len__(self):len(obj)__getitem__(self, key):索引/切片访问__setitem__(self, key, value):索引赋值__contains__(self, item):in运算符
(5)可调用对象
__call__(self):对象像函数一样被调用

6899

被折叠的 条评论
为什么被折叠?



