Python 如何在类创建时使用self.method()?

Python 如何在类创建时使用self.method()?,python,Python,在某些情况下,我希望在创建类时使用实例方法 我只想在权限列表中使用self..这是我的问题 但它不起作用。这是解决问题的方法吗 class PermissionChecker(object): # how to use self in class create time. permissions = [self.is_superuser(), self.is_god()] def is_superuser(self): # use self.proper

在某些情况下,我希望在创建类时使用实例方法


我只想在权限列表中使用self..这是我的问题

但它不起作用。这是解决问题的方法吗

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

您似乎混淆了术语
属性
属性
;不能在类定义本身中使用
self
,它仅对方法可用

我认为您正在寻找:

通过使用
属性
(上面用作
@
装饰器),可以将方法转换为属性:

>>> pcheck = PermissionChecker()
>>> pcheck.permissions
[True, True]
每次对实例访问
.permissions
属性时,都会调用
permissions
方法

或者,在
初始化器中设置列表:

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

看起来您正在尝试提供一个属性。可以这样做:

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

我在您的示例代码中没有看到任何属性。你到底是什么意思?请注意,我所说的属性是指使用
属性
描述符。您不能在
权限
列表中使用
self
;它是在类创建时执行的,而不是在访问
权限时执行的。如果你解释一下你想用它实现什么,我想你的问题会更清楚。对不起,我不知道如何用英语调用self.permissions。所以我称之为类属性..我只想在权限列表中使用self..这是我的问题。你把语法都弄混了;您不能调用
self.\u get\u permissions()
将其作为属性。对不起,我没有清楚解释我的问题。我现在更新它。我更新我的问题。我的问题是如何在权限列表中使用self。@chenchiyuan:没有属性就不能这样做。如果我不想在init方法中定义self,还有其他方法解决这个问题吗?@chenchiyuan:我给了你两种解决方法。不能在类定义中使用
self
;您需要一个方法来绑定它。@chenchiyuan:Last time:
self
在创建类时从未定义过。您需要绑定到
self
的实例。恐怕你解决不了那个问题。在不使用实例的情况下重新定义您的问题,您可以在类创建时解决它。
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