r_31415
r_31415

Reputation: 8980

Passing an instance to __init__. Is this a good idea?

Suppose I have a simple class like this:

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

An instances of Class1 returns a value that can be used in other class:

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

This is working. However, I have the feeling that this is not a very common approach and maybe there are alternatives. Having said this, I tried to refactor my classes to pass simpler objects to Class2, but I found that passing the whole instance as an argument actually simplifies the code significantly. In order to use this, I have to do this:

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

This is very similar to the way some R packages look like. Is there a more "Pythonic" alternative?

Upvotes: 0

Views: 899

Answers (1)

dano
dano

Reputation: 94961

There's nothing wrong with doing that, though in this particular example it looks like you could just as easily do

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

But if you find you need to use other properties/methods of Class1 inside of Class2, just go ahead and pass the whole Class1 instance into Class2. This kind of approach is used all the time in Python and OOP in general. Many common design patterns call for a class to take an instance (or several instances) of other classes: Proxy, Facade, Adapter, etc.

Upvotes: 3

Related Questions