Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

python - Assigning IDs to instances of a class (Pythonic)

I want to have each instance of some class have a unique integer identifier based on the order that I create them, starting with (say) 0. In Java, I could do this with a static class variable. I know I can emulate the same sort of behavior with Python, but what would be the most 'Pythonic' way to do this?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The following approach would be relatively pythonic (for my subjective judgement of pythonic - explicit, yet concise):

class CounterExample(object):

    instances_created = 0

    def __init__(self):
        CounterExample.instances_created += 1

    def __del__(self):
        """ If you want to track the current number of instances
            you can add a hook in __del__. Otherwise use
            __init__ and just count up.
        """
        CounterExample.instances_created -= 1

If you are facing a large number of classes, which need that kind of attribute, you could also consider writing a metaclass for that.

An example of a metaclass: http://www.youtube.com/watch?v=E_kZDvwofHY#t=0h56m10s.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...