我应该如何在Python中引用类变量? [英] How should I refer to class variables in Python?

查看:393
本文介绍了我应该如何在Python中引用类变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我可以从内部使用 ClassName.class_var self.class_var 引用类级变量一类。现在,只要我不通过创建同名的实例变量(我觉得这很愚蠢)来覆盖对象中的类级别变量的名称,它们将始终引用相同的内容。

In Python I can refer to a class level variable with either ClassName.class_var or self.class_var from within a class. Now as long as I do not override the class level variables name within an object by creating an instance variable of the same name (which I find would be kind out silly), they will always refer to the same thing.

我的问题是,哪种方法更好?或更常见?

我看到使用任何一种方式编写代码的书和源代码本身。在某些情况下,我看到它们使用BOTH方法来引用同一类中的变量,而我认为这确实是不一致的。

I see coding books and source code itself using either way. In some cases, I see them using BOTH methods to refer to the variable within the same class which I think is really inconsistent.

这里我提供一个示例:

class Foo(object) :
    class_var = ['same','for','all']
    def __init__(self, instance_var) :
        self.instance_var = instance_var
    def print_words(self) :
        # here I could use self.class_var
        for w in Foo.class_var :
            print w


推荐答案

如果只有一个类,只读变量,不会有太大区别。

If you have only the one class and you only read the variable, you won't see a lot of difference.

如果考虑到子类覆盖 class_var ,然后 self.class_var 首先会在当前类中查找,而 Foo.class_var 将继续具体引用该特定值。最佳做法取决于您的意图,但是由于使用一种使类成为可选语言的类意味着至少对多态性感兴趣,因此 self 可能更有用。

If you take into account the possibility of subclasses that override class_var, then self.class_var will look in the current class first while Foo.class_var will continue to refer concretely to that particular value. The best practice depends on your intent but since using classes in a language that makes them optional implies at least some interest in polymorphism, self is probably more generally useful.

此外,如果要设置值, self.whatever = 将设置一个实例变量,而 Foo.whatever = 会设置类变量,该变量随后也会影响其他实例。

Also, if you want to set the value, self.whatever = will set an instance variable and Foo.whatever = will set the class variable which could then affect any other instance as well.

这篇关于我应该如何在Python中引用类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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