Python 类常用操作涵盖了类的定义、实例化、访问属性和方法、继承、多态以及特殊方法的使用等。下面是一些常用的 Python 类操作示例:
1. 定义类
pythonclass MyClass:
def __init__(self, value):
self.value = value
def my_method(self):
print(self.value)
2. 实例化类
pythonobj = MyClass(10)
3. 访问属性
pythonprint(obj.value) # 输出: 10
4. 调用方法
pythonobj.my_method() # 输出: 10
5. 修改属性
pythonobj.value = 20
print(obj.value) # 输出: 20
6. 继承
pythonclass MyChildClass(MyClass):
def another_method(self):
print("This is a method from MyChildClass")
child_obj = MyChildClass(30)
child_obj.my_method() # 输出: 30
child_obj.another_method() # 输出: This is a method from MyChildClass
7. 多态
多态指的是子类对象可以当作父类对象使用,同样的方法调用用到不同的对象上会有不同的行为。
pythondef process_value(obj):
obj.my_method()
process_value(MyClass(40)) # 输出: 40
process_value(MyChildClass(50)) # 输出: 50
8. 特殊方法
- 构造函数 (
__init__
): 初始化对象 - 析构函数 (
__del__
): 对象销毁前调用 - 字符串表示 (
__str__
和__repr__
): 自定义对象的字符串表示 - 比较操作 (
__eq__
,__ne__
,__lt__
,__gt__
,__le__
,__ge__
): 自定义比较行为 - 算术操作 (
__add__
,__sub__
,__mul__
,__truediv__
, 等): 自定义算术行为 - 访问控制 (
__getattr__
,__setattr__
,__delattr__
): 控制属性访问 - 迭代器 (
__iter__
,__next__
): 允许对象被迭代 - 上下文管理 (
__enter__
,__exit__
): 允许对象用作with
语句的上下文
示例:特殊方法的使用
pythonclass MyIterable:
def __init__(self, start, end):
self.value = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.value >= self.end:
raise StopIteration
current = self.value
self.value += 1
return current
# 使用迭代器
iterable = MyIterable(0, 5)
for i in iterable:
print(i) # 输出: 0, 1, 2, 3, 4
9. 类属性和实例属性
pythonclass MyClassWithClassVar:
class_var = "I am a class variable"
def __init__(self, instance_var):
self.instance_var = instance_var
# 访问类属性
print(MyClassWithClassVar.class_var) # 输出: I am a class variable
# 创建实例并访问实例属性
obj = MyClassWithClassVar("I am an instance variable")
print(obj.instance_var) # 输出: I am an instance variable
10. 类方法和静态方法
pythonclass MyClassWithMethods:
@classmethod
def class_method(cls):
print("This is a class method")
@staticmethod
def static_method():
print("This is a static method")
MyClassWithMethods.class_method() # 输出: This is a class method
MyClassWithMethods.static_method() # 输出: This is a static method
这些操作涵盖了 Python 类的基础用法,根据具体的应用场景,可能还需要使用装饰器、属性装饰器、元类等更高级的特性来扩展类的功能。
1 条评论
2025年10月新盘 做第一批吃螃蟹的人coinsrore.com
新车新盘 嘎嘎稳 嘎嘎靠谱coinsrore.com
新车首发,新的一年,只带想赚米的人coinsrore.com
新盘 上车集合 留下 我要发发 立马进裙coinsrore.com
做了几十年的项目 我总结了最好的一个盘(纯干货)coinsrore.com
新车上路,只带前10个人coinsrore.com
新盘首开 新盘首开 征召客户!!!coinsrore.com
新项目准备上线,寻找志同道合的合作伙伴coinsrore.com
新车即将上线 真正的项目,期待你的参与coinsrore.com
新盘新项目,不再等待,现在就是最佳上车机会!coinsrore.com
新盘新盘 这个月刚上新盘 新车第一个吃螃蟹!coinsrore.com