5_Python OOP
1. 实例属性和类属性
(1) 实例属性在构造函数__init__中定义,定义时以self作为前缀,只能通过实例名访问
(2) 类属性在类中方法之外单独定义,还可以在程序中通过类名增加,建议通过类名直接访问。
class Product: ##建议首字母大写
price = 100 ##类属性
def __init__(self,c):
self.color = c ##实例属性
##主程序
Product1 = Product("red")
Product2 = Product("yellow")
Product.price = 120 ##修改类属性值
Product.name = "shoes" ##增加类属性
Product1.color = "black" ##修改实例属性
(3) 私有属性以__开头,否则是公有属性。私有属性在类外不能直接访问。而是通过特殊方式访问私有属性:
class Food:
def __init__(self):
self.__color = 'red' ##私有属性定义格式
self.price = 0
##主程序
>>>apple = Food()
>>>apple.(_)Food__color = "blue" ##私有属性修改格式
>>>print(apple._Food__color) ##私有属性访问格式
blue
2. 类的方法
class Fruit:
price = 0 ##类属性
def __init__(self):
self.__color = 'red' ##私有属性
def __outputColor(self): ##私有方法
print(self.__color)
def output(self): ##公有方法
self.__outputColor()
@staticmethod ##静态方法
def getprice():
return Fruit.frice
@classmethod ##类方法
def fget(cls):
print(cls)
3. 构造函数和析构函数
def __init__(self,first = '',last = '',id = 0):
self.firstname = first
self.lastname = last
self.idint = id
def __del__(self):
print("self was dead")
4. 常用的运算符重载
方法 | 重载 | 调用 |
---|---|---|
__add__ | + | x+y |
__or__ | | | x|y |
__repr__ | 打印 | repr(x) |
__str__ | 转换 | str(x) |
__call__ | 函数调用 | x(*args,**key) |
__getattr__ | 点号运算 | x.undefine |
__setattr__ | 属性赋值 | x.any=value |
__delattr__ | 属性删除 | del x.any |
__getattribute__ | 属性获取 | x.any |
__getitem__ | [] | x[key] |
__setitem__ | 索引赋值 | x[key]=value |
__delitem__ | 索引删除 | del x[key] |
__len__ | 长度 | len(x) |
__bool__ | 布尔测试 | bool(x) |
__lt__,__gt__ | 小于,大于 | |
__le__,__ge__ | 小于等于,大于等于 | |
__eq__,__ne__ | 等于,不等于 | |
__contain__ | in | item in x |
__iter__,__next__ | 迭代 | I=iter(x),next(x) |
5. 继承
与C++继承实现类似
class sub(super):
def __init__(self):
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 提示词工程师自白:我如何用一个技巧解放自己的生产力
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)
· 如何不购买域名在云服务器上搭建HTTPS服务