我希望有人能给我一些关于我的代码的建议? 我通过自学课程学习python,其中一项要求如下:
创建一个名为蜈蚣.py,包括一个名为“蜈蚣”的类。该类有以下要求:
一旦实例化(如果使用值调用),它会将该参数附加到内部列表:
>>> from centipede import Centipede
>>> ralph = Centipede()
>>> ralph('pretzel')
>>> ralph.stomach
['pretzel']
如果print()类,则返回内部列表的逗号分隔字符串:
>>> ralph('pickles')
>>> print(ralph)
'pretzel,pickles'
每次在蜈蚣对象上设置属性时,它都会将该属性的名称附加到另一个内部列表中:
>>> ralph.shoes = 100
>>> ralph.hat = 1
>>> ralph.legs['shoes', 'hat']
蜈蚣对象的表示形式必须是第二个内部列表的逗号分隔字符串。在
>>> ralph
'shoes,hat'
以下是我目前编写的代码:
class MixIns:
def __setattr__(self, key, value):
print("ATTR: setting attribute {0!r} to {1!r}".format(key, value))
self.__dict__[key] = value
def __getattr__(self, key):
print("ATTR: getting attribute {0!r}".format(key))
self.__setattr__(key, "No value")
return "No value"
class Centipede(MixIns):
legs = []
stomach = []
def __init__(self):
MixIns.__init__(self)
def __str__(self):
return self.name
def __call__(self, *args):
[self.stomach.append(arg) for arg in args]
def __repr__(self):
return ','.join(self.legs)
以下是通过命令行运行上述代码的结果:
我不知道我错在哪里了?在
legs
和{您的
__call__
方法有点太复杂了。这就足够了:如果您
print
一个对象,它将通过__str__
进行转换。你可以试试因此,
__str__
必须返回连接的stomach
为什么是混血儿?魔术方法应该在没有混音的情况下工作。另外,我不知道你想在
__getattr__
和__setattr__
中完成什么,你能详细说明一下吗?相关问题 更多 >
编程相关推荐