Access class when used as class-level variable in Python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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.

Answers

http://en.wikipedia.org/wiki/Trait_%28computer_programming%29 http://en.wikipedia.org/wiki/Trait_%28computer_programming%29

http://code.enthought.com/projects/traits 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    

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/21218284/access-class-when-used-as-class-level-variable-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils