(类变量的用法)pythonic - 或从java学习的讨厌习惯?

mon*_*nny 2 python coding-style class

你好Pythoneers:下面的代码只是模仿我正在尝试做的事情,但它应该说明我的问题.

我想知道这是否是我从Java编程中获取的肮脏技巧,或者是有效的Pythonic做事方式:基本上我是在创建一堆实例,但我需要跟踪所有实例的"静态"数据因为他们被创造了.

class Myclass:
        counter=0
        last_value=None
        def __init__(self,name):
                self.name=name
                Myclass.counter+=1
                Myclass.last_value=name
Run Code Online (Sandbox Code Playgroud)

还有一些使用这个简单类的输出,表明一切都按预期工作:

>>> x=Myclass("hello")
>>> print x.name
hello
>>> print Myclass.last_value
hello
>>> y=Myclass("goodbye")
>>> print y.name
goodbye
>>> print x.name
hello
>>> print Myclass.last_value
goodbye
Run Code Online (Sandbox Code Playgroud)

这是一种普遍接受的做这种事情的方式,还是一种反模式?

[例如,我不太高兴我显然可以在班级(好)和外面(坏)中设置反击; 也不热衷于在类代码本身中使用完整的命名空间'Myclass' - 只是看起来很笨重; 最后我最初将值设置为'None' - 可能我是通过这样做来打扰静态类型的语言?]

我使用的是Python 2.6.2,程序是单线程的.

Mar*_*ton 7

在我看来,类变量完全是Pythonic.

请注意一件事.实例变量可以隐藏类变量:

x.counter = 5  # creates an instance variable in the object x.
print x.counter  # instance variable, prints 5
print y.counter  # class variable, prints 2
print myclass.counter # class variable, prints 2
Run Code Online (Sandbox Code Playgroud)