Reputation: 3464
I have seen this in one the facebook.py User file.
class User(db.Model):
username = db.StringProperty(required=True)
password = db.StringProperty(required=True)
@classmethod
def get_by_email(cls, email):
return cls.query(cls.email == email).get()
What does cls mean? if you put self, it is referring to the User class normally. But what's cls refer to?
Thanks in advance.
Upvotes: 0
Views: 313
Reputation: 86
"cls" is a conventional identifier used to mean "class".
The @classmethod decorator makes a call to the method, ex. obj.method(arg)
, pass to the first parameter (cls in this case) a class object representing the class of the object.
Without the @classmethod decorator, the object itself would be passed to the first parameter (cls in this case).
Upvotes: 3
Reputation: 137310
The name does not matter, but applying classmethod
decorator makes the method a class method. In such case the first argument is a class, not an instance.
Please take a look at the comparison of instance, class and static methods using the following code:
>>> class Test(object):
def instance_method(sth, x):
return sth, x
@classmethod
def class_method(sth, x):
return sth, x
@staticmethod
def static_method(x):
return x
>>> a = Test()
>>> a.instance_method('abc')
(<__main__.Test object at 0x0000000002C26D30>, 'abc')
>>> a.class_method('abc')
(<class '__main__.Test'>, 'abc')
>>> a.static_method('abc')
'abc'
By convention, when you are referring to the same instance, you name it self
. When you are referring to its class, you name it cls
. That is only a convention, but it is better to follow it for consistency.
Upvotes: 4