發現了一個髒解決方法,不是很完美:
class Model:
pass
class rel(object):
def __init__(self,cls):
self.relation = cls;
class a(Model):
pass
class c(Model):
some_other = 4
a = rel(a)
class b(Model):
somevar = 3
a = rel(a);
### Some sort of hack ###
gl = list(globals())
for v in gl:
if type(eval(v)).__name__ == 'classobj':
cls = eval(v);
if len(cls.__bases__) > 0 and cls.__bases__[0].__name__ == "Model":
for atr in dir(cls):
if type(getattr(cls,atr)).__name__ == "rel":
relL = getattr(cls,atr).relation;
print relL.__name__, "->", cls.__name__
setattr(relL,cls.__name__ + "_set",cls)
### End - Some sort of hack ###
d = a();
print a.b_set.somevar
print a.c_set.some_other
輸出:
a -> c
a -> b
3
4
編輯:更好一些骯髒的黑客:
class Model:
### Some sort of hack ###
def __init__(self):
gl = list(globals())
print self.__class__.__name__, "Relations:"
for v in gl:
if type(eval(v)).__name__ == 'classobj':
cls = eval(v)
if len(cls.__bases__) > 0 and cls.__bases__[0].__name__ == "Model":
for atr in dir(cls):
if type(getattr(cls,atr)).__name__ == "rel":
rell = getattr(cls,atr).relation;
if isinstance(self,rell):
print rell.__name__, "<-", cls.__name__
setattr(rell,cls.__name__ + "_set",cls)
### End - Some sort of hack ###
class rel(object):
def __init__(self,cls):
self.relation = cls;
class a(Model):
pass
class c(Model):
some_other = 1
a = rel(a);
class d(Model):
string = "Hello"
c = rel(c)
class b(Model):
somevar = 3
a = rel(a);
d = rel(d);
a = a();
c = c();
print "\nVars:"
print "somevar",":",a.b_set.somevar
print "some_other",":",a.c_set.some_other
輸出:
a Relations:
a <- c
a <- b
c Relations:
c <- d
...
請更新的答案......這看起來像一個拗口令 – Goin
我不知道問題是什麼。 – Sebi2020
這是一個叫做元編程*的黑魔法。看到這個:http://python-3-patterns-idioms-test.readthedocs.org/en/latest/Metaprogramming.html Django在內部使用它。我建議不要走這條路,除非你真的**必須。維護這樣的代碼很困難。如果你不確定你是否需要它,那麼你不需要它。 :) – freakish