我有一个类,在其中我想从静态方法中引用self
。 有没有办法做到这一点?
class User(object):
email = "username"
password = "********"
@staticmethod
def all():
return {"ex": self.password}
print(User.all())
我有一个类,在其中我想从静态方法中引用self
。 有没有办法做到这一点?
class User(object):
email = "username"
password = "********"
@staticmethod
def all():
return {"ex": self.password}
print(User.all())
class User(object):
email = "username"
password = "********"
@classmethod
def all(cls):
return {"ex": cls.password}
print(User.all())
https://docs.python.org/2/library/functions.html#classmethod
typing_extensions
包含Self
,它指的是当前作用域内的类。 - Stephan Samuel不,没有。
staticmethod
的重点在于它不需要实例 (self
) 或类 (通常称为 cls
) 的信息来完成其工作。
如果你的 staticmethod
需要 self
,那么它就不是一个 staticmethod
,你应该普通地定义它。