Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python class with static method and reference to self

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())
like image 276
Gunther Avatar asked Dec 26 '22 07:12

Gunther


1 Answers

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

like image 99
rknuu Avatar answered Dec 31 '22 12:12

rknuu