#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__)