Python中Class里的__contains__(self,x)函數解析


網上搜了一些文章,有點繞.

在Class里添加__contains__(self,x)函數,可判斷我們輸入的數據是否在Class里.參數x就是我們傳入的數據.

如下代碼:

class Graph():
    def __init__(self):
        self.items = {'a':1,'b':2,'c':3}
    def __contains__(self,x): # 判斷一個定點是否包含在里面
        return x in self.items



a = Graph()
print('a' in a) # 返回True
print('d' in a) # 返回False

>> True
>> False
class Graph():
    def __init__(self):
        self.items = {'a':1,'b':2,'c':3}

    def __str__(self):
        return '打印我干嘛'
    
    def __contains__(self,x): # x參數接受的就是我們手動傳遞的數據
        if x<10 and x>0:
            return True
        return False



print(9 in Graph())
print(5 in Graph())
print(51 in Graph())

>> True
>> True
>> False


免責聲明!

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



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