I have a class where I want to reference self
from within a static method. Is there a way to do this?
class User(object):
email = "username"
password = "********"
@staticmethod
def all():
return {"ex": self.password}
print(User.all())
The way to do this is with a classmethod instead. The way this works is that the first argument is the class itself, which you can access your variables using the dot operator.
For example:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With