我希望您对此代码有意见或建议
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Defines the class (Element) that will be used in the Container
class Element:
def __init__(self, address):
# The address is the identifier for this element
self._address = int(address)
def theaddress(self):
# Getter for the address
return self._address
def __eq__(self, other):
# This function will be called if we like to check if this instanse is already a
# member of the container instance
print("A __eq__ called: %r == %r ?" % (self, other))
return self._address == other._address
# Defines the class (Container) which holds n instances of Element class
class Container:
def __init__(self):
# Basically it is a list
self._listcontainers = list()
# If we like to append a new element instance, we have to check if new one is already available
# with the same address. So we like to never had the same address twice or more times!
def appendcontainer(self, possibleElement: Element = Element(1)):
# Calls the __eq__ element of the Element class to check if this one (with exactly this address) is already present
if possibleElement in self._listcontainers:
# If the possibleElement is in the container list
print('Address %i of this element %s is already existing.' % (possibleElement.theaddress(), possibleElement))
return False
else:
# If possobleElement is new append it to the containerlist
self._listcontainers.append(possibleElement)
print('Added element: %s with address: %i' % (possibleElement, possibleElement.theaddress()))
return True
# Returns the available elements in the containers
def lengthcontainers(self):
return len(self._listcontainers)
def main():
# List of containers
myContainer = Container()
# New element with address 1
newElement1 = Element(1)
myContainer.appendcontainer(newElement1)
# New element with address 2
newElement2 = Element(2)
myContainer.appendcontainer(newElement2)
# New element with address xyz
newElement3 = Element(2) # You can play with the addresses...
myContainer.appendcontainer(newElement3)
print('Available elements: %i' % myContainer.lengthcontainers())
if __name__ == "__main__":
main()
__eq__
函数对我来说很有趣。因为_address
应该是一个私有变量,并且我在other._address
->“访问类的受保护成员_address ...”时收到警告。我需要在这里考虑些什么吗?任何意见或建议对我都会很有帮助。其实我只是在做原型,但这应该是在这种情况下保存一些数据的真实项目的基础。
答案 0 :(得分:1)
我认为魔术方法(如__eq__
,__le__
等)(根据代码样式)允许使用other
对象的受保护成员,因此我将忽略警告。
至于附加,我建议尽可能使用set
代替list
。 set
的工作是仅存储不同的元素,而您无需检查元素的存在,set
会为您完成。不要忘记为您的__hash__
类实现Element
方法:
class Element:
...
def __hash__(self):
return hash(self._address)
def __eq__(self, other):
return self._address == other._address