我需要一个像这样的类:
>>> a=Foo()
>>> b=Foo()
>>> c=Foo()
>>> c.i
3
这是我的尝试:
class Foo(object):
i = 0
def __init__(self):
Foo.i += 1
它可以按要求工作,但是我想知道是否还有更多的Python方式可以做到这一点。
不。很好。
摘自Python的禅宗:“简单胜于复杂。”
这很好,并且清楚您在做什么,请不要使其复杂化。也许将其命名为counter
或其他名称,但除此之外,您可以深入研究pythonic。
滥用装饰器和元类。
def counting(cls):
class MetaClass(getattr(cls, '__class__', type)):
__counter = 0
def __new__(meta, name, bases, attrs):
old_init = attrs.get('__init__')
def __init__(*args, **kwargs):
MetaClass.__counter += 1
if old_init: return old_init(*args, **kwargs)
@classmethod
def get_counter(cls):
return MetaClass.__counter
new_attrs = dict(attrs)
new_attrs.update({'__init__': __init__, 'get_counter': get_counter})
return super(MetaClass, meta).__new__(meta, name, bases, new_attrs)
return MetaClass(cls.__name__, cls.__bases__, cls.__dict__)
@counting
class Foo(object):
pass
class Bar(Foo):
pass
print Foo.get_counter() # ==> 0
print Foo().get_counter() # ==> 1
print Bar.get_counter() # ==> 1
print Bar().get_counter() # ==> 2
print Foo.get_counter() # ==> 2
print Foo().get_counter() # ==> 3
您可以通过频繁使用带有双下划线的名称来分辨它是Pythonic。 (开玩笑,开玩笑...)
如果要担心线程安全(以便可以从实例化Foo
的多个线程中修改类变量),则以上答案是正确的。我问了有关线程安全性here的问题。总之,您将必须执行以下操作:
from __future__ import with_statement # for python 2.5
import threading
class Foo(object):
lock = threading.Lock()
instance_count = 0
def __init__(self):
with Foo.lock:
Foo.instance_count += 1
现在Foo
可以从多个线程实例化。
我们可以使用装饰器吗?例如,..
class ClassCallCount:
def __init__(self,dec_f):
self._dec_f = dec_f
self._count = 0
def __call__(self, *args, **kwargs):
self._count +=1
return self._dec_f(*args, **kwargs)
def PrintCalled(self):
return (self._count)
@ClassCallCount
def somefunc(someval):
print ('Value : {0}'.format(someval))
somefunc('val.1')
somefunc('val.2')
somefunc('val.3')
somefunc('val.4')
## Get the # of times the class was called
print ('of times class was called : {0}'.format(somefunc._count))