Skip to main content
 首页 » 编程设计

python之将函数放置在不依赖于状态的类之外

2025年02月15日11虾米哥

在研究最佳软件工程实践时,让我感到困惑的一件事是如何处理不改变状态或以其他方式与状态交互的类中的方法。

在this article我喜欢作者如何讨论数据和逻辑的分离。但是在尝试将其应用于实践时,我遇到了这样的情况:我在类外部有一个奇怪的函数,它不会改变对象的状态,但在对象外部并不真正相关。

例如:

def inspect_color(color): 
    if color == 'brown': 
        return 'Similar to chocolate' 
 
class Dog(object): 
 
   def __init__(self, color): 
       self.color = color 
 
   def play_in_mud(self): 
       self.color = 'brown' 
       results = inspect_color(self.color) 

对比

class Dog(object): 
 
   def __init__(self, color): 
       self.color = color 
 
   def play_in_mud(self): 
       self.color = 'brown' 
       results = self.inspect_color() 
 
    def inspect_color(self): 
        if self.color == 'brown': 
            return 'Similar to chocolate' 

是否有一般的软件工程原则或最佳实践(来自任何合理的范例)建议应遵循这些方法中的哪一个?由于多种原因,我的直觉告诉我顶部的更好,除了这样做:inspect_color(self.color) 困扰我,所以我不确定。我阅读了一些资料,但没有找到针对此类案例的最佳实践的明确答案。

请您参考如下方法:

那是一个staticmethod有利于。

A static method does not receive an implicit first argument.

class Dog(object): 
 
    def __init__(self, color): 
        self.color = color 
 
    def play_in_mud(self): 
        self.color = 'brown' 
        results = self.inspect_color(self.color) 
        return results 
 
    @staticmethod 
    def inspect_color(color): 
        if color == 'brown': 
            return 'Similar to chocolate' 

你可以像函数一样使用它:

>>> Dog.inspect_color('brown') 
'Similar to chocolate' 

在你的方法中:

>>> dog = Dog('red') 
>>> dog.play_in_mud() 
'Similar to chocolate'