【发布时间】:2020-07-15 11:26:32
【问题描述】:
我正在尝试编写一个可以轻松扩展的模拟类。为此,我想使用类似于属性的东西,但它也提供了一个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)
这有可能以某种方式实现,还是有其他方法可以实现类似的行为?我见过this question,这可能会有所帮助,但答案似乎很不优雅——我的案例有没有好的面向对象的方法?
【问题讨论】:
-
如果您基本上只想更新所有类型为 Quantity 或任何派生类的实例变量,请使用 issubclass() 检查 self.__dict__ 中的所有项目,并在 issubclass 返回 true 时对其调用 update
-
@Pablo:John 标记了他的问题 [oop],使用
issubclass()并访问__dict__对我来说听起来恰恰相反。参见例如这些原则:en.wikipedia.org/wiki/SOLID. -
@John:密度和温度是静态成员有什么特殊原因吗?
-
我对 OOP 不太熟悉,甚至不确定静态成员是什么。感谢任何建设性的批评。
-
参见例如en.wikipedia.org/wiki/Class_variable。关键是,一个类的变量对于所有对象(运行时类实例)是否只存在一次(“静态”),或者每个对象都有自己的,允许不同的值(“正常”情况)。在 Python 中,访问权限是
MyClass.a_value与self.a_value。
标签: python oop python-descriptors