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__创建对象过程

相关推荐
IVEN_6 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang8 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮8 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling8 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮11 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽11 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers