1. 程式人生 > >python -- 類中--內置方法

python -- 類中--內置方法

神奇 args __str__ 否則 打印 iss sch __call__ als

isinstance 和 issubclass

isinstance(obj,b) 檢查是否obj是否是類b的對象

class A(object):pass
class B(A):pass
b=B()
print(isinstance(b,B))  #如果b是B的對象  就返回True,反之False
print(isinstance(b,A))  #如果b是A的對象  就返回True,反之False

issubclass(A,B) 檢測B是否繼承A

class A(object):pass
class B(A):pass
print(issubclass(B,A))  #
如果B繼承A 就返回True,反之Fasle

類的內置方法

1)改變對象的字符串顯示 __str__,__repr__

自定制格式化字符串 __format__

技術分享圖片
format_dict={
    nat:{obj.name}-{obj.addr}-{obj.type},#學校名-學校地址-學校類型
    tna:{obj.type}:{obj.name}:{obj.addr},#學校類型:學校名:學校地址
    tan:{obj.type}/{obj.addr}/{obj.name},#學校類型/學校地址/學校名
}
class School:
    
def __init__(self,name,addr,type): self.name=name self.addr=addr self.type=type def __repr__(self): return School(%s,%s) %(self.name,self.addr) def __str__(self): return (%s,%s) %(self.name,self.addr) def __format__(self, format_spec):
# if format_spec if not format_spec or format_spec not in format_dict: format_spec=nat fmt=format_dict[format_spec] return fmt.format(obj=self) s1=School(oldboy1,北京,私立) print(from repr: ,repr(s1)) print(from str: ,str(s1)) print(s1) ‘‘‘ str函數或者print函數--->obj.__str__() repr或者交互式解釋器--->obj.__repr__() <--#__str__的備胎 如果__str__沒有被定義,那麽就會使用__repr__來代替輸出 註意:這倆方法的返回值必須是字符串,否則拋出異常 ‘‘‘ print(format(s1,nat)) print(format(s1,tna)) print(format(s1,tan)) print(format(s1,asfdasdffd))
View Code 技術分享圖片
class B:

     def __str__(self):
         return str : class B  ------%s

     def __repr__(self):
         return repr : class B------%r


b=B()
print(%s%b)
print(%r%b)
%s和%r

2)__del__

析構方法,當對象在內存中被釋放,自動觸發執行.

註意:此方法一般無需定義,因為python是一門高級語言.

技術分享圖片
class Foo:
    def __del__(self):
            print(執行我了)
 f=Foo()
del  f
print(---->)
#輸出結果
執行我了
---->
View Code

3)item系列

__getitem__\__setitem__\__delitem__

技術分享圖片
class Foo:
    def __init__(self,name):
        self.name=name

    def __getitem__(self, item):
        print(self.__dict__[item])   #直接生成字典

    def __setitem__(self, key, value):
        self.__dict__[key]=value
    def __delitem__(self, key):
        print(del obj[key]時,我執行)
        self.__dict__.pop(key)
    def __delattr__(self, item):
        print(del obj.key時,我執行)
        self.__dict__.pop(item)

f1=Foo(sb)
print(f1.name)
f1[age]=18
f1[age1]=19
del f1.age1
del f1[age]
f1[name]=alex
print(f1.__dict__)
View Code

4)__new__ \ __init__(實例化 構造方法(單例模式))/ 初始化方法

技術分享圖片
class A:
    def __init__(self):
        self.x = 1
        print(in init function)
    def __new__(cls, *args, **kwargs):
        print(in new function)
        return object.__new__(A, *args, **kwargs)------提供了一個類實例化的時候提供的一個所需要的內存空間

a = A()
print(a.x)
View Code

5)__call__ (對象後面加括號,觸發執行)

註意:構造方法的執行是由創建對象觸發的,即:對象 = 類名():而對於__call__方法的執行是由對象後加括號觸發的 ,即:對象() 或者 類()

技術分享圖片
class Student():
    def __init__(self,name,age):
        self.name = name
        self.age = age
    # def call(self):pass
    def __call__(self, *args, **kwargs):
        print(調用我啦)
alex = Student(alex,83)-----執行__init__
alex()    ----執行__call__
View Code

6)__len__ (len(對象))

技術分享圖片
class A:
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 1

    def __len__(self):
        return len(self.__dict__)------查的長度
a = A()
print(len(a))
View Code

7)__hash__ (每次執行__hash__都會改變,在一次執行的過程中對同一個值的hash結果總是不變的)

技術分享圖片
class A:
    def __init__(self):
        self.a = 1
        self.b = 2

    def __hash__(self):
        return hash(str(self.a)+str(self.b))
a = A()
print(hash(a))
View Code

8)__eq__( 判斷)

技術分享圖片
class A:
    def __init__(self):
        self.a = 1
        self.b = 2

    def __eq__(self,obj):
        if  self.a == obj.a and self.b == obj.b:
            return True
a = A()
print(a)
b = A()
print(b)
print(a == b)
View Code

9)__iter__和__next__(這兩個方法用於將一個對象模擬成序列)

技術分享圖片
class Num:
    def __init__(self, max_num):
        self.max_num = max_num
        self.count = 0
        
    def __iter__(self):
        return self

    def __next__(self):
        if self.count < self.max_num:
            self.count += 1
            return self.count
        else:
            raise StopIteration(已經到達臨界)
        
num = Num(10)
for i in num:
    print(i)  # 循環打印1---10
View Code

10)__getattr__\__setattr__\__delattr__(訪問,設置和刪除)

技術分享圖片
class Student:
    def __getattr__(self, item):
        print(訪問一個不存在的屬性時候觸發)
        return 不存在

    def __setattr__(self, key, value):
        print(設置一個屬性值的時候觸發)
        # self.key = value  # 這樣會無限循環
        self.__dict__[key] = value

    def __delattr__(self, item):
        print(刪除一個屬性的時候觸發)
        if self.__dict__.get(item, None):
            del self.__dict__[item]

stu = Student()
stu.name = zlw  # 設置一個屬性值的時候觸發
print(stu.noexit)  # 訪問一個不存在的屬性時候觸發 , 返回‘不存在‘
del stu.name  # 刪除一個屬性的時候觸發
View Code

11)__getattribute__(屬性訪問截斷器)

屬性查找順序:

實例的 getattribute-->實例對象字典--.實例所在類字典--->實例所在類的父類(MRO順序)字典-->實例所在類的getattr--->報錯

技術分享圖片
class People:
    a = 200

class Student(People):
    a = 100

    def __init__(self, a):
        self.a = a

    def __getattr__(self, item):
        print(沒有找到:, item)

    def __getattribute__(self, item):
        print(屬性訪問截斷器)
        if item == a:
            return 1
        return super().__getattribute__(item)

stu = Student(1)
print(stu.a)  # 1
View Code

12)__enter__和__exit__

技術分享圖片
class MySQL:
    def connect(self):
        print(啟動數據庫連接,申請系統資源)

    def execute(self):
        print(執行sql命令,操作數據)

    def finish(self):
        print(數據庫連接關閉,清理系統資源)

    def __enter__(self):  # with的時候觸發,並賦給as變量
        self.connect()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):  # 離開with語句塊時觸發
        self.finish()

with MySQL() as mysql:
    mysql.execute()
    
# 結果:
# 啟動數據庫連接,申請系統資源
# 執行sql命令,操作數據
# 數據庫連接關閉,清理系統資源
View Code

13)__doc__ (類的描述信息)

技術分享圖片
class Foo:
    """ 描述類信息,這是用於看片的神奇 """

    def func(self):
        pass

print Foo.__doc__
#輸出:類的描述信息
View Code

14)__module__ 和__class__( 當前操作的對象在那個模塊\當前操作的對象的類是什麽)

技術分享圖片
from lib.aa import C

obj = C()
print obj.__module__  # 輸出 lib.aa,即:輸出模塊
print obj.__class__      # 輸出 lib.aa.C,即:輸出類
View Code 技術分享圖片
class FranchDeck:
    ranks = [str(n) for n in range(2,11)] + list(JQKA)
    suits = [紅心,方板,梅花,黑桃]

    def __init__(self):
        self._cards = [Card(rank,suit) for rank in FranchDeck.ranks
                                        for suit in FranchDeck.suits]

    def __len__(self):
        return len(self._cards)

    def __getitem__(self, item):
        return self._cards[item]

    def __setitem__(self, key, value):
        self._cards[key] = value

deck = FranchDeck()
print(deck[0])
from random import choice
print(choice(deck))
print(choice(deck))

from random import shuffle
shuffle(deck)
print(deck[:5])
紙牌遊戲 技術分享圖片
class Person:
    def __init__(self,name,age,sex):
        self.name = name
        self.age = age
        self.sex = sex

    def __hash__(self):
        return hash(self.name+self.sex)

    def __eq__(self, other):
        if self.name == other.name and self.sex == other.sex:return True


p_lst = []
for i in range(84):
    p_lst.append(Person(egon,i,male))

print(p_lst)
print(set(p_lst))
面試題

希望大家多多關註,多多評論!!!

       

python -- 類中--內置方法