当一个属性依赖于两个类时,它应该定义在哪个类上?

2024-05-14 18:53:46 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个类:WaterSubstance。一个或多个Substance可以溶解在Water中;Water实例具有substances属性,该属性包含Substance实例的列表。aSubstance的扩散常数取决于它所溶解的Water的属性以及Substance本身的一些属性。然后,我应该在Water上创建一个get_diffusion_constant方法,将Substance的实例作为其属性,还是应该将该方法添加到Substance中,其中Water是其参数?还是有完全不同的方法


Tags: 实例方法列表参数get属性常数diffusion
2条回答

你写道:

The diffusion constant of a Substance depends on the attributes of the Water

这让我们认为扩散常数是物质的一个特征,因此Substance类应该拥有允许计算它的方法(带有一个参数来提供Water实例,因为它依赖于它)

这对于大多数简单的情况都很有效,如果一个真正的概念拥有一个特性,那么它的模型(在本例中是一个类)应该拥有相关的属性或方法

一些设计模式和/或更复杂的需求可能有理由打破这一“规则”,引入更多的行动


另外,回答您的评论:将self传递给函数不是问题(至少在IMO是这样)。 self只是对当前实例的引用,没有什么特别之处,只是它是命名当前实例的一个广受尊重的约定,因此是(实例)方法的第一个参数

再解释一下:实例方法必须接受对相关实例的引用作为第一个参数。按照惯例,此位置参数的名称为self,但您可以决定将其命名为thisinstance或任何您想要的名称,它都是相同的。然后您只需要在方法中使用正确的参数名

请参阅下面的代码。它对实例参数使用了非常糟糕的名称,但它的工作方式就像使用了self

class Foo:
    def __init__(current_instance):
        current_instance.bar = 'baz'

    def __str__(this_name_is_ridiculous):
        return this_name_is_ridiculous.bar


print(Foo())  # prints baz

我假设WaterSubstance继承了一些东西。因此,您可以在每个Substance中有一个diffusion_constant,还可以有一个diffuse函数,其中包含一个或多个Substance

编辑:

class Water:
     def diffuse(self, *args):
         #check if args is greater 0 or None and then iterate and apply diffusion_constants

class Substance:
      diffusion_constant = 0 #base constant

class Sirup(Substance):
      diffusion_constant = 3

#somewhere later then
corn_sirup = Sirup()
sugary_sirup = Sirup()
water = Water()
water.diffuse(corn_sirup, sugary_sirup)

编辑: 由于注释,我更改了代码。Python有duck类型,所以只要您的实体有diffusion_constant属性,就可以访问它,不管它是什么。这样就可以了

相关问题 更多 >

    热门问题