Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django when to use @staticmethod or @property

Tags:

python

django

I keep seeing the following decorators used: @staticmethod, @property for example:

@staticmethod
def add_url():
    return reverse('add_user')

@property
def password_not_expired(self):
    return not self.password_expired

Could someone explain when to use one over the other? Say I want to add this code:

def get_user_type(self):
    return self.user_type

I would use a @staticmethod method right?

like image 287
Prometheus Avatar asked Dec 09 '22 08:12

Prometheus


1 Answers

You can't use self in a @staticmethod. Because the only thing @staticmethod does is make the function not be passed self. Look in your own example: add_url doesn't take a self argument.

"static" here is in the entirely misleading sense of how C++ and Java use it. A Python @staticmethod is really just a regular function that happens to live in a class, nothing to do with whether values are changed.

You can use @property without writing a setter. In fact, that's probably the most common way to use it.

like image 77
Eevee Avatar answered Dec 10 '22 20:12

Eevee