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
CamelCase(i.e.MonkeyandMonkeys) and variable/member/function/method names should belowercase_with_underscoresfor the sake of convention. (2) Classes should derive fromobject(class Monkey(object)) in Python 2.x, as "old-style classes" are just cruft and headaches.monkeylist.append(self.name)in your init. Its indented wrong. Only indent for block level. Also its probably not the best idea if you are iterating throough it in theMonkeysclass to alter it in theMonkeyclass IMHO.