sumit-sampang-rai
sumit-sampang-rai

Reputation: 691

Object Oriented Programming: object initialization of a class by passing the instance of other class

I have created a test subject to understand my Object Oriented Programming.

class Asset(object):
    def __init__(self, project):
        self.project = project

    def do_something(self):
        return self.project.x, self.project.y, True


class Project(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.asset = Asset(self) # Is this correct?

    def call_do_something(self):
        return self.asset.do_something()


project_test = Project('foo', 'bar')
project_test.call_do_something()

Can I initialize class Asset as an attribute of class Project by passing the instance of class Project like I have done in self.asset = Asset(self)? If yes, what is the term for it? If not, how can I solve this problem?

Upvotes: 0

Views: 142

Answers (3)

Ranger Wu
Ranger Wu

Reputation: 401

This may be called object composition, and you are mainly expressing: a Project "has a" Assert. In most languages, "field", "property" etc. are used to denote the reference object (Assert here).

For design pattern Composition over inheritance, it may be more complicated: The component and the composite will have the same interface (derived from it), and normally composite will have a list of the components.

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78536

Yes, you perfectly can. This design pattern is called Composition over inheritance

Composition over inheritance (or composite reuse principle) in object-oriented programming is the principle that classes should achieve polymorphic behavior and code reuse by their composition (by containing instances of other classes that implement the desired functionality) rather than inheritance from a base or parent class

Read more

Upvotes: 3

Laurent LAPORTE
Laurent LAPORTE

Reputation: 22942

Yes it is correct.

You can also pass an Asset as a parameter of Project constructor, like this:

class Asset(object):
    def __init__(self, project=None):
        self.project = project

class Project(object):
    def __init__(self, x, y, asset):
        self.x = x
        self.y = y
        self.asset = asset
        self.asset.project = self

That way, you can initialise a project as follow:

project = Project('foo', 'bar', Asset())

The relationship is done automatically by the Project constructor.

Upvotes: 1

Related Questions