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) # 输出: 104. 调用方法
pythonobj.my_method() # 输出: 105. 修改属性
pythonobj.value = 20
print(obj.value) # 输出: 206. 继承
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 MyChildClass7. 多态
多态指的是子类对象可以当作父类对象使用,同样的方法调用用到不同的对象上会有不同的行为。
pythondef process_value(obj):
obj.my_method()
process_value(MyClass(40)) # 输出: 40
process_value(MyChildClass(50)) # 输出: 508. 特殊方法
- 构造函数 (
__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, 49. 类属性和实例属性
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 variable10. 类方法和静态方法
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 类的基础用法,根据具体的应用场景,可能还需要使用装饰器、属性装饰器、元类等更高级的特性来扩展类的功能。
5 条评论
华纳客服开户流程,华纳客服开户流程图(?183-8890--9465—《?薇-STS5099】
新盛开户前客服电话咨询材料清单【1558--7291-507薇同1】
新盛开户官方客服电话 【1558--7291-507 薇同1】
新盛开户业务办理电话 【1558--7291-507 薇同1】
新盛开户联系电话大全 【1558--7291-507 薇同1】
华纳东方明珠官方客服在线咨询?(▲18288362750?《?微信STS5099? 】【╃q 2704132802╃】
华纳总公司开户流程详解?(▲18288362750?《?微信STS5099? 】【╃q 2704132802╃】
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