Python类用静态方法和对self的引用

Gun*_*her 3 python static-methods django-rest-framework

我有一个我想self在静态方法中引用的类.有没有办法做到这一点?

class User(object):
    email = "username"
    password = "********"

    @staticmethod
    def all():
        return {"ex": self.password}


print(User.all())
Run Code Online (Sandbox Code Playgroud)

Eth*_*man 6

不,没有。

a 的要点staticmethod是它不需要实例 ( self) 也不需要类(通常称为cls)信息来完成其工作。

如果您staticmethod需要self,那么它不是 a staticmethod,您应该正常定义它。


小智 6

这样做的方法是使用classmethod.这种方法的工作方式是第一个参数是类本身,您可以使用点运算符访问变量.

例如:

class User(object):
    email = "username"
    password = "********"

    @classmethod
    def all(cls):
        return {"ex": cls.password}


print(User.all())
Run Code Online (Sandbox Code Playgroud)

https://docs.python.org/2/library/functions.html#classmethod