Reputation: 691
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
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
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
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