正如标题所说。无论我做什么,似乎
如果有关于此的文档指针,我将不胜感激。
代码:
感谢BrenBarn,这是最终的可工作实现代码:
__getattr__
都不会被调用。我也试过一个实例(荒谬,我知道),可预见地没有反应。就好像元类中禁止使用__getattr__
一样。如果有关于此的文档指针,我将不胜感激。
代码:
class PreinsertMeta(type):
def resolvedField(self):
if isinstance(self.field, basestring):
tbl, fld = self.field.split(".")
self.field = (tbl, fld)
return self.field
Field = property(resolvedField)
def __getattr__(self, attrname):
if attrname == "field":
if isinstance(self.field, basestring):
tbl, fld = self.field.split(".")
self.field = (tbl, fld)
return self.field
else:
return super(PreinsertMeta, self).__getattr__(attrname)
def __setattr__(self, attrname, value):
super(PreinsertMeta, self).__setattr__(attrname, value)
class Test(object):
__metaclass__ = PreinsertMeta
field = "test.field"
print Test.field # Should already print the tuple
Test.field = "another.field" # __setattr__ gets called nicely
print Test.field # Again with the string?
print Test.Field # note the capital 'F', this actually calls resolvedField() and prints the tuple
感谢BrenBarn,这是最终的可工作实现代码:
class PreinsertMeta(type):
def __getattribute__(self, attrname):
if attrname == "field" and isinstance(object.__getattribute__(self, attrname), basestring):
tbl, fld = object.__getattribute__(self, attrname).split(".")
self.field = (tbl, fld)
return object.__getattribute__(self, attrname)
__getattribute__
:) 关于以上实现的意义:上述实现是针对父类的子类的,其中field
成员不能直接引用基类成员,因为在此时该成员不存在。__getattribute__版本允许我在使用时使用解析后的成员变量。由于封闭类和子类都不会被实例化,因此我试图通过元类来解决这个问题。 - velis