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

相关推荐
用户25191624271111 小时前
Python之语言特点
python
刘立军12 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机15 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机16 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i18 小时前
django中的FBV 和 CBV
python·django
c8i18 小时前
python中的闭包和装饰器
python
这里有鱼汤21 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩1 天前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在1 天前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP2 天前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python