我需要一个Python类来跟踪它被实例化的次数 [英] I need a Python class that keep tracks of how many times it is instantiated

查看:756
本文介绍了我需要一个Python类来跟踪它被实例化的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个这样的类:

>>> a=Foo()
>>> b=Foo()
>>> c=Foo()
>>> c.i
3

这里是我的尝试:

class Foo(object):
    i = 0
    def __init__(self):
        Foo.i += 1

它可以按需工作,但我想知道是否有更多的pythonic方法。

It works as required, but I wonder if there is a more pythonic way to do it.

推荐答案

不。这很不错。

来自Python的禅:简单比复杂更好。

From The Zen of Python: "Simple is better than complex."

罚款,清楚你在做什么,不要使它复杂化。也许把它命名为 counter 或者什么,但除此之外,你还是可以走到pythonic去。

That works fine and is clear on what you're doing, don't complicate it. Maybe name it counter or something, but other than that you're good to go as far as pythonic goes.

这篇关于我需要一个Python类来跟踪它被实例化的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆