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

相关推荐
曲幽6 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户83562907805110 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞13 小时前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派15 小时前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪17 小时前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户03321266636717 小时前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫18 小时前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派19 小时前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
明月_清风21 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽1 天前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic