在Python中,我如何以静态方式泛型引用类,比如PHP的“self”关键词? [英] In Python, how do I reference a class generically in a static way, like PHP's "self" keyword?

查看:137
本文介绍了在Python中,我如何以静态方式泛型引用类,比如PHP的“self”关键词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP类可以在静态上下文中使用关键字self,如下所示:

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.
  }
}
?>

显然我不能在Python中使用self,因为self一个类而不是一个实例。所以有一种方法我可以在Python的静态上下文中引用当前类,类似于PHP的self?

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"?

我想我要做的是相当非pythonic。不知道,我是Python的新手。这里是我的代码(使用Django框架):

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.

推荐答案

这应该可以解决这个问题:

This should do the trick:

class C(object):
    my_var = 'a'

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

C.t()

这篇关于在Python中,我如何以静态方式泛型引用类,比如PHP的“self”关键词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆