【发布时间】:2016-01-10 01:33:24
【问题描述】:
我正在阅读banking application 的源代码,bank 类定义如下:
class Bank(object):
""" the bank class contains all the bank operations """
def __init__(self, name):
""" instantiate the class """
self.name = str(name)
self.customers = Customers()
现在self.customers 是Customers 类的另一个实例,定义如下:
class Customers(dict):
""" the customers class extends the dictionary object """
def __setitem__(self, key, item):
self.__dict__[key] = item
def __getitem__(self, key):
return self.__dict__[key]
def __repr__(self):
return repr(self.__dict__)
def __len__(self):
return len(self.__dict__)
def __delitem__(self, key):
del self.__dict__[key]
def keys(self):
return self.__dict__.keys()
def values(self):
return self.__dict__.values()
def __cmp__(self, dict):
return cmp(self.__dict__, dict)
def __contains__(self, item):
return item in self.__dict__
def add(self, key, value):
self.__dict__[key] = value
def __iter__(self):
return iter(self.__dict__)
def __call__(self):
return self.__dict__
def __unicode__(self):
return unicode(repr(self.__dict__))
- 根据我的理解,我们
override a function在添加新功能或其行为从以前的功能更改时。为什么我们是overridingdict在Customer类中的函数。我们不能简单地使用self.customers = dict()吗?因为我们没有在此处添加任何新内容。
【问题讨论】:
-
这段代码很糟糕,毫无意义,而且有问题。它实际上是两个 dicts,
self和self.__dict__,并且由于只有一些dict 方法被覆盖,一些方法看不到其他方法的操作的效果。例如theBankclass tries to callgetandpop,没有被覆盖,所以添加后找不到客户。__repr__具有误导性,__call__很奇怪,总的来说,这只是糟糕的代码。 -
你能帮我改进一下吗?我还在
Python中编写银行应用程序,希望能得到您的帮助。 -
完全忽略此代码。对于字典,只需使用常规字典而不对其进行子类化。对于银行代码的其余部分,您可以独立于该代码的功能做出自己的设计决策。这段代码不是一个有用的起点。
标签: python class oop inheritance dictionary