python问题求助~谢谢
class Counter:def __init__(self):
super().__setattr__('counter',0)
def __setattr__(self,name,value):
super().__setattr__('counter',self.counter + 1)
super().__setattr__(name, value)
def __delattr__(self,name):
super().__setattr__('counter',self.counter - 1)
super().__delatter__(name)
问题1:请教为什么以上程序标红的两句为什么要用__setattr__来写,为什么不是super().counter,或者super().__delattr__呢?
问题2:当我使用__dict__方法的时候,该怎样写呢,以下是我的错误程序
class Counter:
def __init__(self):
self.__dict__ = 0
def __setattr__(self,name,value):
self.__dict__ += 1
super().__setattr__(name, value)
def __delattr__(self,name):
self.counter -= 1
super().__delatter__(name) 1. Counter 的父类没有 counter 这个属性。
2. __dict__ 是一个字典,访问元素需要使用字符串:
class Counter:
def __init__(self):
self.__dict__['counter'] = 0
def __setattr__(self,name,value):
self.__dict__['counter'] += 1
super().__setattr__(name, value)
def __delattr__(self,name):
self.counter -= 1
super().__delattr__(name)
页:
[1]