【问题标题】:Call method modification issue调用方法修改问题
【发布时间】:2015-06-26 23:14:11
【问题描述】:

根据这个答案Change attribute after each object calling,我认为调用方法应该在每次调用时对其实例做一些事情。我试图在我的代码中使用它,但我在某个地方错了。

class switcher():
    current_index = -1

    def __call__(self):
        self.current_index +=1

sw = switcher()
print sw.current_index
print sw.current_index

输出: -1

输出: -1

我认为它应该返回这个:

输出: 0

输出: 1

因为每次调用 sw 实例时它都会增加current_index 的值。

显然我错了,请你告诉我问题出在哪里?

【问题讨论】:

  • 你永远不会在这段代码中调用任何切换器实例。

标签: python class oop call init


【解决方案1】:

我不知道你真正想做什么,但你需要真正调用你没有做的实例:

sw = switcher() # creates instance, does not call __call__ in your class
sw() # call/increment calling the instance 
print(sw.current_index)
sw() # call/increment calling the instance 
print(sw.current_index)
0 # after first sw() call 
1  # after second sw() call 

__call__ 使您的实例可调用,如果您不调用该实例,则它什么也不做。创建实例与__call__无关

您链接到的答案中的属性方法似乎是您想要做的。

【讨论】:

  • @MalikBrahimi,这与问题无关,与问题完全无关
  • 不,我没有交替使用 callinit,我知道只有在创建实例时才会调用 init。我认为每次“使用”该方法的实例时都会调用 call 。这意味着每当我使用(我认为是调用)属性或方法时。
  • @Milan,调用实例时不使用调用,它使对象可调用,并不意味着每次使用实例访问属性时都会调用它。使用属性是做你想做的事情的唯一合理方法
  • @MalikBrahimi,问题中没有任何内容表明不应共享该变量
  • @PadraicCunningham 感谢您的解释。每当我对实例执行任何操作(例如访问属性或使用方法)时,是否可以使用某些东西来更改属性?我知道我可以使用 __@property 但是有没有像 call 和 init 这样的方法可以做到这一点?
【解决方案2】:

首先:current_index 属性属于类,而不是您需要的对象实例。 您需要在

内分配它
__init__(self) 

第二:调用对象实例,如上一个答案所述。

【讨论】:

  • 这不是惯例问题。类和实例属性的行为完全不同。他说他想对实例进行操作
  • 虽然这不是主要问题,但我同意属性应该是实例属性。
【解决方案3】:

你不明白类的构造方法和调用方法的区别:

__init__ := 'instance is created when class is invoked, Switcher()'
__call__ := 'func is executed when instance is invoked, switcher()'
class Switcher():

    def __init__(self):
        self.current_index = -1

    def __call__(self):
        self.current_index += 1
switcher = Switcher() # instance created calling __init__ -> current_index = -1
switcher() # instance just been invoked, calling __call__ -> current_index = 0

【讨论】:

  • 请记住,您实际上应该只使用属性。
猜你喜欢
  • 2015-04-29
  • 2011-07-24
  • 1970-01-01
  • 2023-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多