警察课程中的勾选方法

时间:2011-03-23 18:28:16

标签: python

我的问题涉及创建一个滴答程序,原始的滴答程序,它使一个名为PoliceOfficer的班级逮捕所有裸体在他周围的人。

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()      

这是原始的滴答方法。

这是我的PoliceOfficer类和称为arrest的方法。逮捕方法逮捕了一个人,因为他们在警察局的区域内没有穿任何衣服,当没有人可以逮捕他只是说了别的话。

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")

对于为PoliceOfficer制作自己的tick方法,这是否部分正确? 如果不是我需要做什么或改变以使其像所描述的滴答方法一样,除非让警察官员逮捕任何没穿衣服的学生?

2 个答案:

答案 0 :(得分:3)

嗯,......你想测试的是一个特定类的对象吗? Python有一个内置函数:isinstance()。快速举例:

>>> isinstance(1, int)
True
>>> isinstance("Hello World!", int)
False
>>> isinstance("Hello World!", str)
True

查看文档以获取更多信息。 http://docs.python.org/library/functions.html#isinstance

根据delnan的“建议”,提出一些建议:不要检查你收到的Person背后的类,让Person实现子类可以覆盖的canBeArrested()方法更清晰, Student可以返回false。

class Person(object):
    (...)
    def canBeArrested(self):
        return True

class Diplomat(Person):
    (...)
    def canBeArrested(self):
        # Overrides Person's default behaviour
        return False

答案 1 :(得分:2)

有两种方法:

obj.__class__.__name__ == "Student"

isinstance(obj, Student)

我建议采用第二种方式,但有时候你真的需要这个类的名称,obj.__class__.__name__就是这样的。