【问题标题】:Is it possible to initialize the argument of a method with a self.variable value from __init__ in python?是否可以在 python 中使用来自 __init__ 的 self.variable 值初始化方法的参数?
【发布时间】:2020-11-15 15:03:30
【问题描述】:

我有一个带有__init__ 方法的类,我在其中定义了一些变量,以及一个方法AddSignalSpectrum

class SpectrumGraph:
    
    # Properties
    def __init__(self):
        self.PlotHeight= 300 
        self.PlotWidth = 800 
        self.xRangeMin = -10 
        self.xRangeMax = 10
        self.yRangeMin = -0.1*(self.xRangeMax - self.xRangeMin)
        self.yRangeMax = 0.9*(self.xRangeMax -self.xRangeMin)

    def AddSignalSpectrum( 
        self,
        name,
        Type,
        CenterPosition,
        Bandwidth=2,
        Height = self.yRangeMax*0.8, 
        Color = "#0000FF", 
        LineWidth = 2,
        AbscissaSymbol = '$\omega_0$',
        ShowLegend = False):
     # Rest of the method

我想要的是为该方法提供 self.yRangeMax*0.8 的默认值,但是当我这样做时,我收到一条错误消息,指出未定义“self”。我可以在方法中使用self 的属性就好了,但它似乎在方法定义的参数中不起作用。我认为这是某种名称空间问题,但找不到解决方法。可能我只是不确定要搜索什么。

【问题讨论】:

    标签: python oop methods


    【解决方案1】:

    这不是初始化,而是为函数参数设置默认值。问题不在于命名空间,而在于 binding

    这些值提前确定一次,并作为函数(或方法)对象的一部分存储。此处无法使用self 参数的属性,因为在发生这种情况时没有。普通函数也是一样的:

    def example(a, b=a+3): # doesn't work; `a` is not defined ahead of time
        print(f'a={a} and b={b}')
    

    正常的解决方法是使用None 作为默认值,然后在逻辑中明确检查并用所需的计算替换None

    def example(a, b=None): # works
        if b is None:
            b = a + 3
        print(f'a={a} and b={b}')
    
    # and now we can call:
    example(1) # 'a=1 and b=4'
    

    【讨论】:

      【解决方案2】:

      通常的做法是设置一个标记值(惯用的None),然后在方法内部定义行为,例如:

      def Dog:
          def __init__(self, name, friend):
              self.name = name
              self.friend = friend
      
          def say_hello(self, other=None):
              if other is None:
                  other = self.friend
      
              print(f"Hello {other}, I'm {self.name}! How are you? Bark!")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-27
        • 2017-07-13
        • 2023-03-28
        • 2022-08-14
        • 2021-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多