A Diskoid is a thing that has a width of 10, a hopping distance of 10, and a longevity of 20. A Diskoid also has an age, a strength, and a location that vary from one to the other. Diskoids know how to move and to determine if they're out of bounds.
When a Diskoid is instantiated, it gets an initial age of 0, an initial strength of 100, and a random location in the world. It also gets a pointer to the world that it belongs to.
list is a class.list is list(), so we can create a new list
(an instance object) by calling it.
>>> newlist = list() >>> newlist [] >>> len(newlist) 0 >>> isinstance(newlist, list) True
list constructor can also take an argument.
For example, we can pass it a tuple, and it returns a list with the same elements.
>>> list((1, 2, 3)) [1, 2, 3]
list, str, and
dict.
>>> newlist.append('a')
>>> newlist
['a']
>>> 'a simple string'.split()
['a', 'simple', 'string']
help(<class>) gives us all of the methods associated with a class, once it's been defined.
class, followed by any superclasses of the class in parentheses. If it has no superclasses, use no arguments at all.
class classname(superclass):
statement
statement
...
>>> class Diskoid: ... '''A thing that moves around and eats Plasmoids.''' >>> Diskoid <class __main__.Diskoid at 0xe69bd0> >>> diskoid1 = Diskoid() >>> isinstance(diskoid1, Diskoid) True
>>> diskoid1.loc = (10, 10) >>> diskoid2 = Diskoid() >>> diskoid2.loc = (8, 8) >>> diskoid1.loc (10, 10) >>> diskoid2.loc (8, 8) >>> diskoid3 = Diskoid() >>> diskoid3.loc ... AttributeError: Diskoid instance has no attribute 'loc'
>>> class World:
... '''A space in which various things live.'''
...
>>> WORLD = World()
>>> WORLD.things = {}
>>> WORLD.things['diskoids'] = []
>>> WORLD.things['diskoids'].append(Diskoid())
>>> WORLD.things['diskoids'][0].loc = (0, 0)
>>> WORLD.things['diskoids'].append(Diskoid())
>>> WORLD.things['diskoids'][1].loc = (5, 5)
>>> for diskoid in WORLD.things['diskoids']:
... print(diskoid.loc)
(0, 0)
(5, 5)
__class__, which is their class object.>>> class Diskoid: ... '''A thing that moves around and eats Plasmoids.''' ... color = 'yellow' ... >>> diskoid1, diskoid2 = Diskoid(), Diskoid() >>> diskoid1.color 'yellow' >>> Diskoid.color 'yellow'
dir.
>>> diskoid1 = Diskoid() >>> diskoid1.loc = (1, 3) >>> dir(diskoid1) ['__class__', '__delattr__', '__dict__', '__doc__', ..., 'color', 'loc']
food to the Diskoid class, bound to the class of the diskoids' food.
You will also need to define the class for the food.
instance.method(arguments)
class.method(instance, arguments...)
>>> [4, 3, 2, 1, 2, 3, 4].count(4)
2
>>> list.count([4, 3, 2, 1, 2, 3, 4], 4)
2
>>> data = "3,280,150,29"
>>> data.split(',')
['3', '280', '150', '29']
>>> str.split(data, ',')
['3', '280', '150', '29']
>>> data.split <built-in method split of str object at 0xe15b38>
list method extend, the dict method items, and the str method replace.
import random
class Diskoid:
def set_loc(self, width, height):
'''Assign a random location to Diskoid instance.'''
self.loc = [random.randint(0, width),
random.randint(0, height)]
self gets bound to an instance of Diskoid when this method is called.
(Because this is a parameter, it can actually have any name, but it is conventional in Python to call it
self.)
>>> diskoid1 = Diskoid() >>> Diskoid.set_loc(diskoid1, 10, 10) >>> diskoid1.loc [6, 3]
>>> diskoid2 = Diskoid() >>> diskoid2.set_loc(10, 10) >>> diskoid2.loc [1, 9]
>>> diskoid1.set_loc(10) Traceback (most recent call last): File "", line 1, in diskoid1.set_loc(10) TypeError: set_loc() takes exactly 3 arguments (2 given)
Diskoid method edible that takes a thing and returns True if the thing belongs to the class of the diskoid's food.Diskoid method init that initializes the diskoid's age at 0 and strength at 10.Diskoid method strengthen that takes a positive or negative strength increment and adds it to the diskoid's strength.World method add_thing that takes a thing and adds it to the things dictionary in the world (this dictionary must already have been created when the method is called).__init__ is called.__init__ in your class definition. This overrides the built-in __init__ method.
__init__ should not return anything.things dictionary so we don't have to bother to do it.
>>> class World:
... def __init__(self):
... '''Initialize the things dict.'''
... self.things = {}
...
>>> WORLD = World()
>>> WORLD.things
{}
__init__ method to the Diskoid class that initializes all diskoids' ages at 0 and strengths at 100.
__init__ method parameters in addition to self, these become arguments to the constructor for the class.
>>> class World:
... def __init__(self, dims):
... """Initialize the things dict and assign the world's dimensions."""
... self.things = {}
... self.width = dims[0]
... self.height = dims[1]
...
>>> WORLD = World((10, 10))
>>> WORLD.width
10
>>> WORLD2 = World()
Traceback (most recent call last):
File "", line 1, in
TypeError: __init__() takes exactly 2 arguments (1 given)
__init__ method optional arguments.
>>> class World:
... def __init__(self, dims=(10, 10), things={}):
... """Initialize the things dict and assign the world's dimensions."""
... self.things = things
... self.width, self.height = dims[0], dims[1]
...
>>> WORLD = World()
>>> WORLD.height
10
Diskoid __init__ method so that it optionally assigns a world to the diskoid and then sets the diskoid's location in case there is a world.__str__.
This controls how instances of the class print out (or what happens when you call the function str on them). You can override this method in a class
definition. __str__ must return a string.
class Diskoid:
def __str__(self):
return '<D' + str(self.loc) + '>'