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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM