時間:2023-05-08 04:45:02 | 來源:網(wǎng)站運(yùn)營
時間:2023-05-08 04:45:02 來源:網(wǎng)站運(yùn)營
python命名空間:def func(): a = 1func()print(a)
運(yùn)行結(jié)果:NameError: name 'a' is not defined
3、在內(nèi)置: 不能使用局部和全局的名字的內(nèi)置>全局>局部
def max(): print("in max func")max()
運(yùn)行結(jié)果:in max func
在正常情況下,直接使用內(nèi)置的名字 當(dāng)我們在全局定義了和內(nèi)置名字空間中同名的名字時,就會使用全局的名字 一級一級找# 函數(shù)名() 函數(shù)的調(diào)用# 加入id 就是函數(shù)的內(nèi)存地址def max(): print("in max func")print(max)print(id(max))
運(yùn)行結(jié)果:<function max at 0x0000025D7091D9D8>2600343820760
class ClassDemo(object): def run(self): raise NotImplementedErrorclass ChildClass(ClassDemo): def run(self): print("Hello world")ChildClass().run()
class ClassDemo(object): def run(self): raise NotImplementedError def wrong(self): # Will raise a TypeError NotImplemented = "don't do this" return NotImplementedclass ChildClass(ClassDemo): def run(self): print("Hello world") def wrong(self): print("wrong")ChildClass().run() # Hello worldwrong = ClassDemo().wrong()print(wrong) # don't do this
這里區(qū)分下 NotImplemented && NotImplementedErrortype(NotImplemented)<class 'NotImplementedType'> type(NotImplementedError)<class 'type'>issubclass(NotImplementedError,Exception)True
NotImplemented 是 Python 內(nèi)建命名空間內(nèi)僅有的 6 個常量(Python 中沒有真正的常量)之一, 其它幾個分別是 False、True、None、Ellipsis 和__debug__
。__eq__()、__lt__()
等等,表示該類型無法和其它類型進(jìn)行對應(yīng)的二元運(yùn)算class A(object): def __init__(self, value): self.value = value def __eq__(self, other): if isinstance(other, A): print('Comparing an A with an A') return other.value == self.value if isinstance(other, B): print('Comparing an A with a B') return other.value == self.value print('Could not compare A with the other class') return NotImplementedclass B(object): def __init__(self, value): self.value = value def __eq__(self, other): # raise NotImplementedError if isinstance(other, B): print('Comparing a B with another B') return other.value == self.value print('Could not compare B with the other class') return NotImplementeda, b = A(1), B(1)aa, bb = A(1), B(1)a == aa # Trueb == bb # Truea == b # Trueb == a # True
運(yùn)行結(jié)果:Comparing an A with an AComparing a B with another BComparing an A with a B
說明 == 運(yùn)算符執(zhí)行時會先尋找 B 的 __eq__()
方法, 遇到 NotImplemented 返回值則反過來去尋找 A 的 __eq__()
方法。NotImplementedError 是 RuntimeError 的子類: issubclass(NotImplementedError, RuntimeError) # True
官網(wǎng) 的建議是當(dāng)你需要一個方法必須覆蓋才能使用時,其效果類似于 Java 中的接口,用于定義一個未實(shí)現(xiàn)的抽象方法。
關(guān)鍵詞:空間,命名
客戶&案例
營銷資訊
關(guān)于我們
微信公眾號
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。