假设我有一个像这样的简单类:
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包的外观非常相似。还有更“ Pythonic”的选择吗?
这样做没有错,尽管在这个特定示例中,您似乎可以轻松完成
instance_of_class2 = Class2(instance_of_class1.property, other_property=other_value).
但是,如果您发现需要使用Class1
内部的其他属性/方法Class2
,只需继续并将整个Class1
实例传递到中即可Class2
。通常在Python和OOP中一直使用这种方法。许多常见的设计模式都要求一个类采用其他类的一个或多个实例:代理,外观,适配器等。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句