【问题标题】:Calling a function inside a function in python3 [duplicate]在python3中调用函数内部的函数[重复]
【发布时间】:2016-10-07 04:17:39
【问题描述】:

我有一个类,并试图在类中的一个函数内创建一个函数。我的代码是这样的:

class example:
    def __init__(self):
        self.points = 0
    def operations(self):
        def add(self):
            self.points += 1
        def subtract(self):
            self.points -= 1
    def display(self):
        print(self.points)

obj = example()
obj.display()
obj.operations.add()

我得到输出0然后得到错误:

obj.operations.add()
AttributeError: 'function' object has no attribute 'add'

我尝试了许多其他方法来解决这个问题,但都没有奏效。 如果您知道如何解决此错误,请回答。

-谢谢

【问题讨论】:

  • 你到底想做什么?您可以在函数内部定义函数,但通过function1.function2 将无法使用它们。特别是只要您不执行该功能,它们甚至都不存在(如果您之后不“保存”这些功能,它们将不复存在)。
  • 函数内部的函数是locals,就像函数中的任何其他变量一样。它们仅在函数调用期间存在,而不是在该调用之外。您是否出于某种原因想要命名这些函数?
  • @MartijnPieters 我之所以在A函数里面有一个函数是因为在我的实际程序中,我有很多程序,我是一个喜欢保持整洁的人。
  • @Nic:这并没有让它更整洁。例如,偏离常规做法会使您的代码更难维护。无论如何,函数不能用于创建额外的命名空间。
  • 除了operations,你还要在那个对象上实现什么?

标签: python function class python-3.x


【解决方案1】:

你可以尝试从函数返回函数,然后像这样使用它们 -

class example:
    def __init__(self):
        self.points = 0
    def operations(self):
        def add():
            print "add is called"
            self.points += 1
        def subtract():
            self.points -= 1
        return [add, subtract]
    def display(self):
        print(self.points)

obj = example()
obj.display()
obj.operations()[0]()
obj.display()

如果你特别想用obj.operations.add() 来做,你可以尝试以这种方式聚合(它涉及到类变量的使用,如果你可以的话)

class example:
    points = 0
    def __init__(self):
        example.points = 0
        self.operations = Operations(self)

    def display(self):
        print(self.points)

class Operations(example):
    def __init__(self, ex):
        self.points = ex.points

    def add(self):
        print "add is called"
        example.points += 1
    def subtract(self):
        example.points -= 1

obj = example()
obj.display()
obj.operations.add()
obj.display()
obj.operations.subtract()
obj.display()

希望对你有帮助!

【讨论】:

  • 我还是想去“obj.operations.add()”。但是,您的方式仍然有效,如果我找不到其他方式,我会使用这种方式。谢谢!
  • 如果你返回一个命名元组,你可以获得 obj.operations().add。如果操作是一个属性,它返回一个命名元组,你将拥有 obj.operations.add。但是……不要那样做。
  • 类示例成功了!谢谢!
  • 类示例使用类属性。是的,它恰好可以工作,但是一旦您使用多个实例,您就会看到共享数据。将example 实例存储在Operations 实例中,并改为引用self.example.points
  • @MartijnPieters 你能举个例子吗?
猜你喜欢
  • 1970-01-01
  • 2017-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-27
  • 1970-01-01
  • 2013-05-28
  • 1970-01-01
相关资源
最近更新 更多