28

PHP classes can use the keyword "self" in a static context, like this:

<?php
class Test {
  public static $myvar = 'a';
  public static function t() {
     echo self::$myvar; // Generically reference the current class.
     echo Test::$myvar; // Same thing, but not generic.
  }
}
?>

Obviously I can't use "self" in this way in Python because "self" refers not to a class but to an instance. So is there a way I can reference the current class in a static context in Python, similar to PHP's "self"?

I guess what I'm trying to do is rather un-pythonic. Not sure though, I'm new to Python. Here is my code (using the Django framework):

class Friendship(models.Model):
  def addfriend(self, friend):
    """does some stuff"""

  @staticmethod # declared "staticmethod", not "classmethod"
  def user_addfriend(user, friend): # static version of above method
    userf = Friendship(user=user) # creating instance of the current class
    userf.addfriend(friend) # calls above method

# later ....
Friendship.user_addfriend(u, f) # works

My code works as expected. I just wanted to know: is there a keyword I could use on the first line of the static method instead of "Friendship"?

This way if the class name changes, the static method won't have to be edited. As it stands the static method would have to be edited if the class name changes.

4
  • when I try to use self.__class__ inside a static method, I get global name 'self' is not defined
    – Eddified
    Commented Apr 10, 2009 at 18:42
  • Are you still passing "self" to the method? Remember that "self" is a parameter name, not a keyword. Commented Apr 10, 2009 at 18:44
  • 1
    @Eddified: that probably should have been a comment on the answer, not the question
    – David Z
    Commented Apr 10, 2009 at 18:47
  • Please post the Python code that isn't working.
    – S.Lott
    Commented Apr 10, 2009 at 18:53

2 Answers 2

37

This should do the trick:

class C(object):
    my_var = 'a'

    @classmethod
    def t(cls):
        print cls.my_var

C.t()
0
30

In all cases, self.__class__ is an object's class.

http://docs.python.org/library/stdtypes.html#special-attributes

In the (very) rare case where you are trying to mess with static methods, you actually need classmethod for this.

class AllStatic( object ):
    @classmethod
    def aMethod( cls, arg ):
        # cls is the owning class for this method 

x = AllStatic()
x.aMethod( 3.14 )
2
  • Am I supposed to be passing "self" to a static function? @staticmethod def blah(): ...
    – Eddified
    Commented Apr 10, 2009 at 18:52
  • No you're not. A static method in general doesn't need any arguments.
    – David Z
    Commented Apr 10, 2009 at 19:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.