python面向对象--类的内置函数
#isinstance(obj,cls)判断obj是否是类cls的实例 #issubclass(cls,cls1)判断cls是否是cls1的子类或派生类 class Foo: pass class Bar(Foo): pass print(issubclass(Bar,Foo))#检查sub类是否是super类的派生类 f1=Foo() print(isinstance(f1,Foo))#检查是否obj是否是类cls对象
#自定义格式化的format方法 x='{0}{0}{0}'.format("dog") print(x) format_dic={ 'ymd':"{0.year}{0.mon}{0.day}", "m-d-y":"{0.mon}-{0.day}-{0.year}", "y:m:d":"{0.year}:{0.mon}:{0.day}" } class Date: def __init__(self,year,mon,day): self.year=year self.mon=mon self.day=day def __format__(self, format_spec):#改写系统内置的format属性 print("我执行了") print("-->",format_spec) if format_spec: fm=format_dic[format_spec] return fm.format(d1) else: return "为空" d1=Date(2016,12,26) #format(d1)#d1.__format__() print(format(d1))#d1.__format__() print(format(d1,"ymd")) d1.name="alex" print(d1.name) # x='{0.year}{0.mon}{0.day}'.format(d1) # print(x)
###改变字符串的显示方法 str,repr
# l=list("hello") # # print(l) # class Foo: # def __str__(self): # return "自己定制的对象的显示方式" # # f1=Foo() # print(f1)#-->str(f1)-->f1.__str__() # file=open("test.txt","w") # print(file) #自己定制str方法 class Foo: def __init__(self,name,age): self.name=name self.age=age # def __str__(self):#当前str与repr共存 # return "这是str" # # def __repr__(self):#repr或者交互式解释器 # return "名字是%s 年龄是%s" %(self.name,self.age) f1=Foo("egon",19) #repr(f1)-->f1.__repr__() # print(f1)#str(f1)--->f1.__str__()----->f1.__repr__() f1.__str__() print(str(f1))
#call方法,对象通过()访问 class Foo: def __call__(self, *args, **kwargs): print("实例执行了obj") f1=Foo() f1()#foo下的.__call__ Foo()#abc下的__call__
#通过类的next和iter实现迭代器协议 class Foo: def __init__(self,n): self.n=n def __iter__(self): return self def __next__(self): if self.n==100: raise StopIteration("终止了") self.n+=1 return self.n # l=list('hello') # for i in l: # print(i) f1=Foo(10) print(next(f1)) print(next(f1)) print(f1.__next__()) for i in f1: #f1.__iter__() ==iter(f1) print(i)#next(f1) for循环捕捉异常终止
class Fib:
def __init__(self):
self.a=1
self.b=1
def __iter__(self):
return self
def __next__(self):
self.a,self.b=self.b, self.a+self.b
if self.b>100:
raise StopIteration("终止了")
return self.a
f1=Fib()
print(next(f1))
print(next(f1))
print(next(f1))
print(next(f1))
print(next(f1))
print(next(f1))
print(next(f1))
print(next(f1))
print("=====>")
for i in f1:
print(i)
class Foo: # __slots__ = ["name","age"]#{"name":none,"age":"none"} __slots__ = "name"#限定实例的数据属性,节省内存 f1=Foo() f1.name="egon" print(f1.name) #f1.age=18 #__setattr__---->f1.__dict__["age"]=18 # print(f1.__dict__) print(f1.__slots__) print(f1.__slots__)
如果我失败了,至少我尝试过,不会因为痛失机会而后悔
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法