我一直在清理我正在扩展的模块中的一些代码,我似乎无法找到Pythonify此代码的方法:
global_next_id = 1
class Obj:
def __init__(self):
global global_next_id
self.id = global_next_id
global_next_id += 1
Run Code Online (Sandbox Code Playgroud)
此代码使用全局id来跟踪类的实例(我也需要self.id内部变量,它需要是一个数字).
任何人都可以建议一种Python化此代码的方法吗?
g.d*_*d.c 53
尝试这样的事情:
from itertools import count
class Obj(object):
_ids = count(0)
def __init__(self):
self.id = next(self._ids)
Run Code Online (Sandbox Code Playgroud)
这是一种在没有后代类共享相同 id/count 的情况下计算实例的方法。元类用于为每个类创建单独的 id 计数器。
元类使用 Python 3 语法。
import itertools
class InstanceCounterMeta(type):
""" Metaclass to make instance counter not share count with descendants
"""
def __init__(cls, name, bases, attrs):
super().__init__(name, bases, attrs)
cls._ids = itertools.count(1)
class InstanceCounter(object, metaclass=InstanceCounterMeta):
""" Mixin to add automatic ID generation
"""
def __init__(self):
self.id = next(self.__class__._ids)
Run Code Online (Sandbox Code Playgroud)
这应该做的工作:
class Obj:
_counter = 0
def __init__(self):
Obj._counter += 1
self.id = Obj._counter
Run Code Online (Sandbox Code Playgroud)
小智 6
我找到了以下解决方案:
class Obj:
counter = 0
def __init__(self):
type(self).counter += 1
def __del__(self):
type(self).counter -= 1
Run Code Online (Sandbox Code Playgroud)
最好使用type(self).counter而不是Obj.counter