[英]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. 因此,为了实践Python,更具体地理解面向对象的编程,我编写了这个简单的脚本来更好地理解这些概念。 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?
然而,当我尝试发起一个“猴子”对象时,最终发生的事情是Python无限期地添加了我的第一个猴子对象的名字......我接近OOP对吗? 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 假设您使用名称列表初始化
Monkeys
,而不是
self.allmonkeys[name] = monkey(name)
I think you want 我想你想要的
self.monkeydict[name] = monkey(name)
FYI the Python naming convention is that classes be uppercased. 仅供参考,Python命名约定是类是大写的。 Also I don't think
Monkeys
is a descriptive name; 我也不认为
Monkeys
是一个描述性的名字; Zoo
might be better. Zoo
可能会更好。 Note also that monkeylist
is a confusing name for a list of names (ie not a list of Monkey
s). 另请注意,
monkeylist
是名称列表的混淆名称(即不是Monkey
的列表)。
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. OOP本身并不是目的。 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).
在这种情况下,使用OOP为猴子集合创建了一个容易陷入错误的空间(这就是为什么我认为我会发布这个作为答案而不是评论)。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.