Skip to main content
 首页 » 编程设计

python之一个类中多个方法的if条件

2025年05月04日17jyk

我使用 Python 编写代码是为了更好地了解使用类时的良好做法。我已经为几个类(class)编写了一些方法;狗和人。我为 dog 引入了一种名为 die 的新方法,定义如下:

def die(self): 
    if self.owner: 
        self.owner.pets.discard(self) 
    self.owner = None 
    self.dead = True 

现在我不希望能够对死狗使用大多数其他方法,即对人采用宠物的方法 (person.adopt(self,pet))。由于这种情况有很多方法(可能还会有更多),我想避免在每个方法中添加一个 if 语句,要求狗还活着。有没有一种方法可以在给定条件(例如 self.dead == False)的情况下简单地不允许某些方法?

请您参考如下方法:

使用装饰器怎么样?您将不得不装饰每个需要宠物活着的函数,但您将避免一遍又一遍地编写 if 逻辑:

>>> def require_alive(func): 
...     def wrapper(self, *args, **kwargs): 
...         if not self.alive: 
...             raise Exception("Not alive") 
...         return func(self, *args, **kwargs) 
...     return wrapper 
... 
>>> def require_hungry(func): 
...     def wrapper(self, *args, **kwargs): 
...         if not self.hungry: 
...             print "Not hungry..." 
...         else: 
...             return func(self, *args, **kwargs) 
...     return wrapper 
... 
>>> class Pet(object): 
...     def __init__(self): 
...         self.alive = True 
...         self.hungry = True 
...     def die(self): 
...         self.alive = False 
...     @require_alive 
...     @require_hungry 
...     def eat(self): 
...         print "Eating..." 
...         self.hungry = False 
...     @require_alive 
...     def sleep(self): 
...         print "Sleeping..." 
... 
>>> roofus = Pet() 
>>> roofus.eat() 
Eating... 
>>> roofus.eat() 
Not hungry... 
>>> roofus.sleep() 
Sleeping... 
>>> roofus.die() 
>>> roofus.eat() 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "<stdin>", line 4, in wrapper 
Exception: Not alive