Search code examples
pythonclassclass-variables

Access class when used as class-level variable in Python


I do apologize if this question is already answered on SO or if my problem could be solved by a simple Google search, but I don't know the terminology to describe it, other than the question title, which didn't turn up any results.

Because I don't know the terminology, the best I can do is give an example of what I want.

class MyClassProperty():
    def __init__(self):
        # somehow access MyObject class
        pass

class MyObject():
    var = MyClassProperty()

MyClassProperty will not only need to reference the MyObject class, otherwise it would be simple. The end goal is to be able to automatically add methods and variables to the MyObject class when a MyClassProperty is instantiated at class level.

I have seen frameworks and libraries do this before, the one that first comes to mind is Kivy, with its properties.

Thanks for any help you can give, even if the extent of that help is to tell me this is impossible.


Solution

  • It looks like you might want traits.

    The only existing Python implementation I could find on a cursory search is here: http://code.enthought.com/projects/traits.

    Multiple inheritance might also work for you.

    class Some(object):
      a = 97
      b = 98
      def f(self):
        return self.a + self.b + self.c
    
    class Other(object):
      c = 99
    
    class Thing(Some, Other, object):
      pass
    
    o = Thing()
    p = Thing()
    p.a, p.b, p.c = 65, 66, 67
    
    print o.a, o.b, o.c, o.f() # 97 98 99 294
    print p.a, p.b, p.c, p.f() # 65 66 67 198