【问题标题】:Influencing class variables with functions that are method's variables使用作为方法变量的函数影响类变量
【发布时间】:2018-08-25 22:53:56
【问题描述】:

假设我有一个类,该类有一个将函数作为参数的方法。有没有办法让这个函数改变类变量?

def f():
    # something here to change MyClass.var

class MyClass:
    def __init__():
        self.var = 1

    def method(self, func):
        #does something
        func()

obj = MyClass()
obj.method(f)
print(obj.var)

【问题讨论】:

  • self 传递给func
  • 尝试调用 obj.method(f) 应该会抛出一个错误,说 expected 1 arguments, found 2,因为如果你说 obj.<method>,python 期望相应的方法定义有一个 self 参数
  • 已更正,谢谢
  • 这个的用例是什么?

标签: python function oop variables


【解决方案1】:

只需将类的内部引用 - self - 传递给函数:

>>> class Class:
        def __init__(self):
            self.var = 1

        def method(self, func):
            func(self)

>>> def func(inst):
        inst.var = 0


>>> cls = Class()
>>> cls.var
1
>>> cls.method(func)
>>> cls.var
0
>>> 

在一个相关的旁注中,我认为实际上让你的函数成为你的类的方法会更清晰:

>>> from types import MethodType
>>> 
>>> def func(self):
        self.var = 0


>>> class Class:
        def __init__(self):
            self.var = 1


>>> cls = Class()
>>> cls.var
1
>>> cls.func = MethodType(func, cls)
>>> cls.func()
>>> cls.var
0
>>> 

【讨论】:

    【解决方案2】:

    由于函数f是在类范围之外定义的,所以它不能访问类变量。但是,您可以将类变量作为参数传递给 f,在这种情况下,它将能够对其执行任何操作。

    def f(x):
        return x**2  # just for the demonstration. Will square the existing value\\
      # of the class variable
    
    
    class MyClass:
    
        def __init__(self):
            self.var = 2
    
        def method(self, func):
            #does something
            self.var = func(self.var)
    
    obj = MyClass()
    obj.method(f)
    print(obj.var)   
    >>> 4
    

    【讨论】:

      【解决方案3】:

      这应该可行:

      def f(obj):
          obj.var = 2
      
      class MyClass:
          def __init__(self):
              self.var = 1
      
          def method(self, func):
              # does something
              func(self)
      
      obj = MyClass()
      obj.method(f)
      print(obj.var)  # --> 2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-12
        • 2013-06-19
        • 1970-01-01
        • 2011-07-29
        • 1970-01-01
        • 2017-09-09
        相关资源
        最近更新 更多