【问题标题】:Is it allowed to add output of a method into self?是否允许将方法的输出添加到 self 中?
【发布时间】:2021-07-03 02:13:16
【问题描述】:

我有一个有几种方法的类。方法的输出用于其他方法。我不想将这些变量作为输入参数传递给其他方法(以使代码更简单)。 我可以将此方法的输出添加到 self 中,以便我可以在其他方法中访问这些变量。

但是,我想确定它是一个标准实现。我担心它可能会导致不可预测的错误。如果您有这方面的经验,请告诉我以下示例是否正确实现。

class MyClass:
    
    def method_1(self, A):
        return A + 1
        
    def method_2(self):
        return self.B + 10

    def method_3(self, C):
        self.B = self.method_1(C) 
        result = self.method_2()
        return result

z = MyClass()
z.method_3(1)

在上面的例子中,我不需要将self.B 传递给method_2。此代码有效,但我想确定它是一种标准方式。

我做的实际程序很复杂,所以我为这个问题做了一个简单的例子。

【问题讨论】:

    标签: python class self


    【解决方案1】:

    是的,它或多或少是正确的,但执行此类操作的标准方法是使用 __init__() 方法并使用函数注释。

    class MyClass:
        def __init__(self) -> None:
            self.B = 0
    
        def method_1(self, A: int) -> int:
            return A + 1
            
        def method_2(self) -> int:
            return self.B + 10
    
        def method_3(self, C: int) -> int:
            self.B = self.method_1(C) 
            result = self.method_2()
            return result
    
    z = MyClass()
    z.method_3(1)
    

    【讨论】:

    • 注释与问题有什么关系?我对打字的所有方面都不是很熟悉。
    • 我认为这里要强调的关键是为self.B 设置一个合理的默认值。如果没有,这个解决方案就不会真正起作用。不过,在这种情况下,将B 设为__init__() 的参数可能会起作用。
    【解决方案2】:

    如果method_2() 依赖于可能未设置的属性,请将其设为私有,以免人们想使用它。例如,如果我这样做会怎样?

    >>> z = MyClass()
    >>> z.method_2()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "tmp.py", line 9, in method_2
        return self.B + 10
    AttributeError: 'MyClass' object has no attribute 'B'
    

    就此而言,最好也将属性设为私有。所以:

    class MyClass:
        
        def method_1(self, A):
            return A + 1
            
        def _method_2(self):
            return self._B + 10
    
        def method_3(self, C):
            self._B = self.method_1(C) 
            result = self._method_2()
            return result
    

    顺便说一句,如果method_1() 不使用self,请考虑将其设为staticmethod

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 2015-07-30
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多