将实例传递给__init__. 这是个好主意吗?

0 投票
1 回答
855 浏览
提问于 2025-04-18 07:47

假设我有一个简单的类,像这样:

class Class1(object):
  def __init__(self, property):
    self.property = property
  def method1(self):
    pass

这个类的实例可以返回一个值,这个值可以在其他类中使用:

class Class2(object):
  def __init__(self, instance_of_class1, other_property):
    self.other_property = other_property
    self.instance_of_class1 = instance_of_class1
  def method1(self):
    # A method that uses self.instance_of_class1.property and self.other_property

这样是可以工作的。不过,我觉得这不是一种很常见的方法,可能还有其他的选择。于是,我尝试重构我的类,想把更简单的对象传给Class2,但我发现把整个实例作为参数传递其实让代码变得更简单。为了使用这个,我需要这样做:

instance_of_class1 = Class1(property=value)
instance_of_class2 = Class2(instance_of_class1, other_property=other_value)
instance_of_class2.method1()

这和一些R语言的包的写法很像。有没有更“Python风格”的替代方案呢?

1 个回答

3

这样做没有什么问题,不过在这个具体的例子里,你其实可以更简单地这样做:

instance_of_class2 = Class2(instance_of_class1.property, other_property=other_value).

但是如果你发现需要在Class2里面使用Class1的其他属性或方法,那就直接把整个Class1的实例传给Class2吧。这种做法在Python和面向对象编程中是非常常见的。很多常见的设计模式都要求一个类接受其他类的实例(或者多个实例),比如代理模式、外观模式、适配器模式等等。

撰写回答