Python help Advanced Objects: Special Methods
I am hoping someone can give me some advice on my code? I am learning python via a self study course and one of the assgnments requirements is as below:
create a program named centipede.py, including a class named "Centipede." This class has the following requirements:
Once instantiated if called with a value, it appends that argument to an internal list:
>>> from centipede import Centipede >>> ralph = Centipede() >>> ralph('pretzel') >>> ralph.stomach ['pretzel']
If you print() the class, it returns a comma-delimited string of the internal list:
>>> ralph('pickles') >>> print(ralph) 'pretzel,pickles'
Each time an attribute is set on the centipede object, it appends the name of the attribute to another internal list:
>>> ralph.shoes = 100 >>> ralph.hat = 1 >>> ralph.legs['shoes', 'hat']
The representation of the centipede object must be a comma-delimited string of this second internal list.
>>> ralph 'shoes,hat'
Here is the code I have written so far:
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)
These are the outcomes of running the code above via the command-line:
- Sort of works I can create an instance but can't set the attribute
- Print doesn't display a list
- I can set the attributes but 'ralph.legs' doesn't return anything
- Doesn't work
I can't figure out where I am going wrong?
legs
andstomach
have to be assigned in the constructor. If you assign them at class level, they are class variables (roughly equivalent to java's static members). Do it like thisdef __init__(self): self.legs = [] self.stomach = []
your
__call__
method is a little too complicated. this should be enough:def __call__(self, item): self.stomach.append(item)
if you
print
an object, it gets converted via__str__
. You can try that withclass Tester(object): def __str__(self): return 'str' print Tester()
so, your
__str__
has to return the joinedstomach
why the mixin? The magic methods should work without mixins. also, im not sure what you are trying to accomplish in
__getattr__
and__setattr__
, could you please elaborate?
精彩评论