2024-07-05 15:44:46 发布
网友
我已经从正在扩展的模块中清理了一些代码,但似乎找不到方法来对这些代码进行Pythonify:
global_next_id = 1 class Obj: def __init__(self): global global_next_id self.id = global_next_id global_next_id += 1
这段代码使用一个全局id来跟踪类的实例(我在内部也需要变量self.id,它需要一个数字)。
self.id
有人能建议一种方法来把这段代码搞得像Python一样吗?
试试这样的:
from itertools import count class Obj(object): _ids = count(0) def __init__(self): self.id = next(self._ids)
下面是一种计算实例的方法,不需要子类共享相同的id/count。元类用于为每个类创建单独的id计数器。
对元类使用Python3语法。
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)
这应该可以做到:
class Obj: _counter = 0 def __init__(self): Obj._counter += 1 self.id = Obj._counter
试试这样的:
下面是一种计算实例的方法,不需要子类共享相同的id/count。元类用于为每个类创建单独的id计数器。
对元类使用Python3语法。
这应该可以做到:
相关问题 更多 >
编程相关推荐