Tick method in a PoliceOfficer class
My question deals with creating a tick procedure the original tick procedure where it makes a class called PoliceOfficer arrest everyone who is naked around him.
def tick(self):
# next time step for all objects that tick
for t in self.__things:
obj = self.get_thing(t)
if has_method(obj, "tick"):
obj.tick()
This the original tick method.
This is my PoliceOfficer
class and the method known as arrest
. The arrest method arrests someone based upon them not having any clothes on when in the area of the PoliceOfficer, and when there isn't anyone to arrest he just says something else.
class PoliceOfficer (Person):
def __init__(self, name, jail):
Person.__init__(self, name)
self.set_restlessness(0.5)
self.__jail = jail
def arrest (self, Person):
if self.location.name is Person.location.name:
self.say (Person.name + "You're under arrest!")
self.say ("You have the right to shut up and lay on the ground with your hands behind your back")
Person.name(Place("jail")
else:
return self.say (Person.name + "Ain't got nothing to do damnit")
def tick (self):
if isinstance(t, Student):
if Student.is_dressed = False:
arrest.student
else:
(Person)tick(): self.say("Shoot no one to arrest off to the 7 eleven")
Would this be partially correct on making my own tick method for PoliceOfficer? If not what else would I need to do or change to make it like the tick me开发者_StackOverflow中文版thod described, except for making the PoliceOfficer arrest any student that isn't dressed?
Uhm,... you want to test is an object is of a certain class? Python has a built-in function for that: isinstance()
. Quick example:
>>> isinstance(1, int)
True
>>> isinstance("Hello World!", int)
False
>>> isinstance("Hello World!", str)
True
Check the documentation for more information. http://docs.python.org/library/functions.html#isinstance
As per delnan's "suggestion", a little piece of advice: instead of checking for the class behind the Person you receive, it's cleaner to have Person
implement a canBeArrested()
method that subclasses can override, for which Student
can return false.
class Person(object):
(...)
def canBeArrested(self):
return True
class Diplomat(Person):
(...)
def canBeArrested(self):
# Overrides Person's default behaviour
return False
There are two ways:
obj.__class__.__name__ == "Student"
or
isinstance(obj, Student)
I recommend the second way, but sometimes you really need the name of the class, for which obj.__class__.__name__
is the way to go.
精彩评论