假设我有这样一个简单的类:
class Class1(object):
def __init__(self, property):
self.property = property
def method1(self):
pass
Class1的实例返回一个可以在其他类中使用的值:
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化"的替代方案?
这样做没有错,尽管在这个特定的示例中,看起来您可以轻松地执行
instance_of_class2 = Class2(instance_of_class1.property, other_property=other_value).
但是如果您发现需要在Class2
中使用Class1
的其他属性/方法,只需继续将整个Class1
实例传递到Class2
。这种方法通常在Python和OOP中一直使用。许多常见的设计模式要求一个类接受其他类的一个实例(或几个实例):Proxy、Facade、Adapter等。