5

簡単に拡張できるシミュレーション クラスを作成しようとしています。このために、プロパティに似たものを使用したいと思いますが、それはupdateさまざまなユース ケースに対して異なる方法で実装できるメソッドも提供します。

class Quantity(object):
    
    def __init__(self, initval=None):
        self.value = initval

    def __get__(self, instance, owner):
        return self.value

    def __set__(self, instance, value):
        self.value = value
    
    def update(self, parent):
        """here the quantity should be updated using also values from
        MySimulation, e.g. adding `MySimulation.increment`, but I don't
        know how to link to the parent simulation."""

        
class MySimulation(object):
    "this default simulation has only density"
    density = Quantity()
    increment = 1
    
    def __init__(self, value):
        self.density = value
    
    def update(self):
        """this one does not work because self.density returns value
        which is a numpy array in the example and thus we cannot access
        the update method"""
        self.density.update(self)

デフォルトのシミュレーションは、次のように使用できます。

sim = MySimulation(np.arange(5))

# we can get the values like this
print(sim.density)
> [0, 1, 2, 3, 4]

# we can call update and all quantities should update
sim.update()  # <- this one is not possible

シミュレーションをユーザー定義の方法で拡張できるような方法で記述したいと思います。たとえば、別の方法で更新される別の数量を追加します。

class Temperature(Quantity):
    def update(self, parent):
        "here we define how to update a temperature"


class MySimulation2(MySimulation):
    "an improved simulation that also evolves temperature"
    temperature = Temperature()
    
    def __init__(self, density_value, temperature_value):
        super().__init__(density_value)
        self.temperature = temperature_value
    
    def update(self):
        self.density.update(self)
        self.temperature.update(self)

それはどういうわけか可能ですか、それとも同様の動作を実現する別の方法はありますか? 私はこの質問を見たことがありますが、それは役立つかもしれませんが、答えは非常に洗練されていないようです - 私の場合、良いオブジェクト指向のアプローチはありますか?

4

2 に答える 2