Is this code snippet pythonic

J

jnair

My Tead Lead 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 waht woutld be the pythonic way
 
P

Peter Hansen

My Tead Lead my object counter code seen below is not pythonic

I'm guessing this was supposed to say "My team lead says my ...." (?)
class E(object):
_count = 0
def __init__(self):
E._count += 1
count = property(lambda self: E._count )

Is this supposed to work in a threaded environment? If so, you'll at
least need to add an acquire/release pair using a threading.Lock()...
if not waht woutld be the pythonic way

Other comments:

1. Why the property? Can't you just access ._count directly?

2. You don't need the "self" in the lambda, since you're not using it
anyway.

3. There aren't any comments. At the least there ought to be one above
"_count = 0" telling the reader what the variable is for.

4. Why are you asking us? The term "pythonic" doesn't have a fixed
definition, so asking your "Tead Lead" makes more sense. From us you
might learn something, but the result might still not satisfy the one
person you need to satisfy with this. Maybe all he wants is to see a
getter method instead of the lambda...

-Peter
 
K

Kent Johnson

2. You don't need the "self" in the lambda, since you're not using it
anyway.

Yes he does, it's a property getter, it will be called with self as an
argument.

Kent
 
F

Felipe Almeida Lessa

Em Seg, 2006-04-10 às 03:52 -0700, (e-mail address removed) escreveu:
My Tead Lead my object counter code seen below is not pythonic

As Peter said, you should really ask your Tead Lead, but what about:

class E(object):
"""Holds a class-wide counter incremented when it's instantiated."""
count = 0

def __init__(self):
# One instance, increment the counter
E.count += 1


def test():
"""Test the counter class E."""
e1 = E()
assert e1.count == 1
print e1.count

e2 = E()
assert e2.count == 2
print e2.count

e3 = E()
assert e3.count == 3
print e3.count

if __name__ == '__main__':
test()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top