[英]how to self-reference a class in Python?
我希望这个Template类接受type(i) in self._allowed_types
的自身的孩子以及其他类型的type(i) in self._allowed_types
。
class Template():
_allowed_types = [str, Template, SafeHtml]
上面的代码抛出了这个:
NameError: name 'Template' is not defined
在类定义后添加类:
class Template():
_allowed_types = [str, SafeHtml]
Template._allowed_types.append(Template)
类主体,根据需要,运行可创建的类对象之前,故得名Template
尚未确定。 但是,您始终可以在创建对象后更改类属性。
另一种(也许是更清洁的方法)是声明一个中间类:
class BasicTemplate():
pass
class Template(BasicTemplate):
_allowed_types = [str, BasicTemplate]
BasicTemplate
可以完全是虚拟的,也可以包含一些有用的代码。 具有不允许包括本身可能会派上用场,在某些点的模板。
当然,这将需要isinstance
而不是type()
来检查类型,但这还是一个好主意。
另一种选择是使用属性来使该字段变得懒惰。
class Test(object):
@property
def allowed(self):
return [str, Test]
t = Test()
print Test in t.allowed
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.