simpy

simpy.core.Enviroment

基于事件的模拟执行环境, 通过从一个事件到另外一个事件来模拟时间的流逝。您可以为环境提供初始的时间,默认情况下,它从零开始。

作者为了提升效率绑定BoundClass实例到env

    def __init__(self, initial_time=0):
        self._now = initial_time
        self._queue = []  # The list of all currently scheduled events. 当前计划事件的列表
        self._eid = count()  # Counter for event IDs  为事件计算ID
        self._active_proc = None

        # Bind all BoundClass instances to "self" to improve performance. 绑定Boundclass 实例 到 self 来提升效率
        BoundClass.bind_early(self)

simpy.core.BoundClass

源代码如下

class BoundClass(object):
    """Allows classes to behave like methods.

    The ``__get__()`` descriptor is basically identical to
    ``function.__get__()`` and binds the first argument of the ``cls`` to the
    descriptor instance.

    """
    def __init__(self, cls):
        self.cls = cls

    def __get__(self, obj, type=None):
        if obj is None:
            return self.cls
        return types.MethodType(self.cls, obj)

    @staticmethod
    def bind_early(instance):
        """Bind all :class:`BoundClass` attributes of the *instance's* class
        to the instance itself to increase performance."""
        cls = type(instance)
        for name, obj in cls.__dict__.items():
            if type(obj) is BoundClass:
                bound_class = getattr(instance, name)
                setattr(instance, name, bound_class)

允许类的行为像方法,将一个类绑定到一个对象上,结合 bind_early方法使得我们可以使用如下方法去使用Process 这个类,我们可以像使用方法一样使用这个Process类

env = simpy.Enviroment()
env.process(生成器方法)

python 中 types.MethodType 的理解

直接上代码

import types

class Person:
	def __init__(self, name=None, age=None):
		self.name = name
		self.age = age
class Run():
	def __init__(self, P, long):
		self.name = P.name
		self.age = P.age
		
		print("{}年龄{}跑了{}小时".format(self.name, self.age, long))
P = Person("小明", "25")
P.Run = types.MethodType(Run, P)
P.Run('5')

posted @ 2021-06-09 11:14  GWZHG  阅读(426)  评论(0)    收藏  举报