Is this object counter code pythonic
Fredrik Lundh
fredrik at pythonware.com
Mon Apr 10 07:21:10 EDT 2006
jnair at ensim.com wrote:
> My Team Lead says my object counter code seen below is not pythonic
>
> class E(object):
> _count = 0
> def __init__(self):
> E._count += 1
> count = property(lambda self: E._count )
>
> def test():
> if __name__ == "__main__":
> e1 = E()
> print e1.count
> e2 = E()
> print e2.count
> e3 = E()
> print e3.count
>
> test()
>
> if not what would be the pythonic way
why are you using a getter (the property) instead of just exposing the
attribute ? why not just do
class E(object):
count = 0 # instance counter
def __init__(self):
E.count += 1
?
and this is a bit backwards:
> def test():
> if __name__ == "__main__":
> /code/
> test()
I suspect you meant to write:
if __name__ == "__main__":
def test():
/code/
test()
or even
if __name__ == "__main__":
/code/
</F>
More information about the Python-list
mailing list