python学习--特殊方法和属性

名称 描述
特殊属性 dict 获得类对象或实例对象所绑定的所有属性和方法的字典
特殊方法 len() 通过重写_len_()方法,让内置函数len()的参数可以是自定义的类型
特殊方法 add() 通过重写_add_()方式,,可使自定义对象有'+'的功能
特殊方法 new() 用于创建对象
特殊方法 init() 对创建的对象进行初始化

特殊属性

python 复制代码
class A:
  pass
class B:
  pass
class C(A,B):
  def _init_(self,name,age):
    self.name=name
    self.age=age
#创建C类的对象
x=C('Jack',20)
print(x.__dict__)#实例对象属性字典
print(C.__dict__)
print(c.__class__)#输出对象所属的类
print(C.__base__)#类的基类
print(C.__mro__)#类的层次结构
print(A.__subclasses__)#子类的列表

特殊方法

python 复制代码
a=20
b=100
c=a+b
d=a.__add__(b)
print(c)#120
print(d)#120
class Student:
  def __init__(self,name):
    self.name=name
  def __add__(self,other):
    return self.name+other.name
  def __len__(self):
    return len(self.name)
stu1=Student('张三')
stu2=Student('李四')
s=stu1+stu2 #实现了两个对象的加法运算(因为在Student类中编写__add__()特殊的方法)
print(s)
lst=[11,22,33,44]
print(len(lst))#len是内置函数len
print(lst.__len__())
print(len(stu1))

__new__与__init__创建对象过程

相关推荐
荣码3 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵13 小时前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li15 小时前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸20 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学21 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽2 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry