到目前为止,我还没有找到这个问题的答案(更多的是一般的Python问题,而不是py2neo的明确) 我希望能够灵活地调用py2neo类:
class foo1(GraphObject):
__primarykey__ = "bar"
bar = Property()
foobar = RelatedTo("foo1")
foobar2 = RelatedTo("foo1")
class foo2(GraphObject):
__primarykey__ = "bar"
bar = ""
foobar = RelatedTo("foo2")
foobar2 = RelatedTo("foo2")
def flexiblefoocreate(classname,newbar):
#classname is "foo1" or "foo2"
tempvar=classname()
tempvar.bar=newbar
def flexiblefoobaradding(classname,startbar,foobarname,endbar)
#classname is "foo1" or "foo2"
#foobarname is "foobar" or "foobar2"
startfoo=classname()
startfoo.bar=startbar
endfoo=classname()
endfoo.bar=endbar
startfoo.foobarname.add(endfoo)
我怎样才能使这个工作?
背景: 稍后轻松添加/使用属性
答案 0 :(得分:0)
您可以使用元类:
class Foo1(object):
def d1(self):
print(self, ".d1")
class Foo2(object):
def d2(self):
print(self, ".d2")
def make_class(base):
return type(str(base), (base,), {})
MyExtraordinarilyNamedFoo1Class = make_class(Foo1)
MySimpleFoo2Class = make_class(Foo2)
foo1 = MyExtraordinarilyNamedFoo1Class()
foo2 = MySimpleFoo2Class()
foo1.d1()
foo1.new_attr = 1
print(foo1.new_attr)
foo2.d2()
foo2.new_attr = 2
print(foo2.new_attr)