在尝试编写__call__覆盖时,如何在Python中嵌套类

时间:2016-12-25 09:29:58

标签: python function python-3.x class object

所以希望下面说明我的观点。我想设置一次translate属性,然后能够将任何mod(如translate)传递给modLevels函数。我知道如何做到这一点的唯一方法是通过嵌套类,但我无法弄清楚如何访问外部类点。任何想法,或者甚至让我知道如果我这样做是错的。谢谢!

class PointSet:
  def __init__(self, points):
     self.points = points

  class translate:
     def __init__(self, xmove=0, ymove=0):
        self.xmove = xmove
        self.ymove = ymove
     def __call__(self):
        for p in Outer.points: # <-- this part isnt working
           p.x += self.xmove; p.y += self.ymove

def modLevels(levels, *mods):
  for lev in range(levels):
     for mod in mods:
        mod

set1 = PointSet(...list of point objects here...)
coolMod = translate(xmove=5)
change(5, coolMod)

2 个答案:

答案 0 :(得分:2)

将其作为参数传递。

    > dput(tmp.df.lhs.denorm[1:2])
structure(list(rules = c("{} => {Dental anesthetic products-Injectables cartridges|2288210-Septocaine Cart 4% w/EPI}", 
"{Dental small equipment-Water distiller parts & acc|5528005-EzeeKleen 2.5HD UV Lamp1,Dental small equipment-Water distiller parts & acc|5528005-EzeeKleen 2.5HD UV Lamp2} => {Dental small equipment-Water distiller parts & acc|5528004-EzeeKleen 2.5HD RO Membra}"
), support = c(0.501710236989983, 0.000610798924993892), confidence = c(0.501710236989983, 
1), lift = c(1, 1637.2), rule.id = 1:2, lhs_1 = c(NA, "Dental small equipment-Water distiller parts & acc|5528005-EzeeKleen 2.5HD UV Lamp1"
), lhs_2 = c(NA, "Dental small equipment-Water distiller parts & acc|5528005-EzeeKleen 2.5HD UV Lamp2"
)), .Names = c("rules", "support", "confidence", "lift", "rule.id", 
"lhs_1", "lhs_2"), class = c("data.table", "data.frame"), row.names = c(NA, 
-2L), .internal.selfref = <pointer: 0x0000000007120788>)

自包含的例子:

class PointSet:
    def __init__(self, points):
        self.points = points

    class translate:
        def __init__(self, xmove=0, ymove=0, parent):
            self.parent = parent
            self.xmove = xmove
            self.ymove = ymove
    def __call__(self):
        for p in self.parent.points:
            p.x += self.xmove; p.y += self.ymove

但是,正如评论中所解释的那样,您根本不需要嵌套类。

class A:
    def __init__(self):
        self.data = [1,2,3]
    class B:
        def __init__(self, parent):
            self.data = [4,5,6]
            self.parent = parent
        def access(self):
            print(self.parent.data)

a = A()
b = a.B(a)
b.access()

答案 1 :(得分:0)

谢谢大家的帮助。我找到了一种在ubuntu论坛上访问外部类的方法。 Solved referencing outer class from an inner class。 我需要这样做以将一些参数传递给转换构造函数,然后覆盖调用函数以使用这些参数。这与C ++函数对象的概念类似,就像传递给STL算法的那样:more on function objects