python-類-實時檢測對象有多少個屬性

運行效果:

c = Counter()
c.x = 1
print(c.counter)

>>> 1

c.y = 2
c.z = 3
print(c.counter)

>>> 3

print(c.attr_name)

>>> [x, y, z]

代碼如下:

class Counter:

    def __init__(self):
            self.counter = 0    # 計算實例中屬性個數
            self.attr_name = []  # 儲存實例中的屬性名

    def __setattr__(self, name, value):
            if name != 'counter' and name != 'attr_name':
                    if name not in self.attr_name:
                            self.counter += 1
                            self.attr_name.append(name)
            super().__setattr__(name, value)

    def __delattr__(self, name):
            self.counter -= 1
            self.attr_name.remove(name)
            super().__delattr__(name)
            
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章