[英]How to use self.method() in class creation time?
In some cases, I want to use instance method in class creation time. 在某些情况下,我想在类创建时使用实例方法。
I just want to use self in permissions list..This is my question 我只想在权限列表中使用self ..这是我的问题
But it does not work. 但这行不通。 Is it some ways to solve the problem? 有解决问题的方法吗?
class PermissionChecker(object):
# how to use self in class create time.
permissions = [self.is_superuser(), self.is_god()]
def is_superuser(self):
# use self.property just like self.name...
return True
def is_god(self):
return True
class Child(PermissionChecker):
permissions = PermissionChecker.permissions + [self.is_coder(),]
def is_coder(self):
return True
It looks like you are confusing the term attribute
with property
; 看来您正在将术语“ attribute
与“ property
混淆; you cannot use self
in the class definition itself, it is only available to a method. 您不能在类定义本身中使用self
,它仅可用于方法。
I think you are looking for the property
descriptor : 我认为您正在寻找property
描述符 :
class PermissionChecker(object):
@property
def permissions(self):
return [self.is_superuser(), self.is_god()]
def is_superuser(self):
# use self.property just like self.name...
return True
def is_god(self):
return True
By using property
(above used as a @
decorator) you turn a method into an attribute: 通过使用property
(以上用作@
装饰器),可以将方法转换为属性:
>>> pcheck = PermissionChecker()
>>> pcheck.permissions
[True, True]
The permissions
method is called every time the .permissions
attribute is accessed on an instance. 每次在实例上访问.permissions
属性时, .permissions
调用permissions
方法。
Alternatively, set the list in the __init__
initializer: 或者,在__init__
初始化程序中设置列表:
class PermissionChecker(object):
def __init__(self):
self.permissions = [self.is_superuser(), self.is_god()]
def is_superuser(self):
# use self.property just like self.name...
return True
def is_god(self):
return True
It looks like you are trying to provide a property. 您似乎正在尝试提供财产。 This can be done like so: 可以这样完成:
class PermissionChecker(object):
def _get_permissions(self):
return [self.is_superuser(), self.is_god()]
permissions = property(_get_permissions)
def is_superuser(self):
# use self.property just like self.name...
return True
def is_god(self):
return True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.