开发者

Object Oriented Python

So in the interest of practicing Python and more specifically understanding object oriented programing I have written this simple script to better understand the concepts. However when I try to initiate a "monkeys" object what ends up happening is Python adds the name of my first monkey object indefinitely... Am I approaching OOP right? And if so, where am I going wrong开发者_开发问答, because I can't tell... Thanks

#! usr/bin/python
monkeylist = []
class monkey:
    def __init__(self, name):
       self.name = name
       self.banana = []
               monkeylist.append(self.name)
    def addbanana(self, kind):
       self.banana.append(kind)

class monkeys:
    def __init__(self, monkeylist):
        self.allmonkeys = monkeylist
        self.monkeydict = {}
        for name in self.allmonkeys:
            self.allmonkeys[name] = monkey(name)
    def addbanana(self, name, kind):
       self.monkeydict[name].addbanana(kind)

The exact input and output is this...

python -i objtest.py
>>> bob = monkey("bob")
>>> test = monkeys(monkeylist)
^CTraceback (most recent call last):
File "<stdin>", line 1, in <module>
File "objtest.py", line 15, in __init__
self.allmonkeys[name] = monkey(name)
File "objtest.py", line 7, in __init__
monkeylist.append(self.name)
KeyboardInterrupt


Assuming you initialise a Monkeys with a list of names, instead of

self.allmonkeys[name] = monkey(name)

I think you want

self.monkeydict[name] = monkey(name)

FYI the Python naming convention is that classes be uppercased. Also I don't think Monkeys is a descriptive name; Zoo might be better. Note also that monkeylist is a confusing name for a list of names (i.e. not a list of Monkeys).


Your code could do with a bit of a clean-up. The monkeys class is redundant, since it merely embodies the dict it contains. You could simply write this:

mm = dict((name, monkey(name)) for name in monkeylist)
mm['harold'].addbanana('green')

OOP is not an end in its own right. Use it when it simplifies things. In this case, using OOP for the monkeys collection created room for a bug to creep in (which is why I thought I'd post this as an answer rather than a comment).


You probably want instead of:

for name in self.allmonkeys:
    self.allmonkeys[name] = monkey(name)

this

for name in self.allmonkeys:
    self.monkeydict[name] = monkey(name)

Or even:

self.monkeydict = dict((name, monkey(name)) for name in allmonkeys) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜