[英]flexible class name using python (py2neo Metaclasses used)
到現在為止,我還沒有找到這個問題的答案(比py2neo的顯式表達式更常見的Python問題),我希望能夠靈活地調用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)
我該如何工作?
背景:稍后輕松添加/使用屬性
您可以使用元類:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.