简体   繁体   中英

How to Nested Classes in Python when trying to write a __call__ overwrite

So hopefully below illustrates my point. I want to set the translate attributes once and then be able to pass any mods (like translate) into the modLevels function. The only way I know how to do this is through nested classes, but I can't figure out how to get access to the outer class points. Any ideas or maybe even let me know if I'm going about this all wrong. THANKS!

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)

Pass it as a parameter.

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

Self-contained example:

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()

However, as explained in comments, you don't need a nested class at all.

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

    def translate(self, x, y):
        for p in self.points:
            p.x += x
            p.y += y

Thank you all for your help. I found a way to access the outer class on ubuntu forums. Solved referencing outer class from an inner class . I needed to do this to pass a few parameters to the translation constructor and then overwrite the call function to use those parameters. This is a similar concept to a C++ function object like what you would pass to an STL algorithm: more on function objects .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM