Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Class instantiated within another class – Beginner question

Sorry in advance for the very basic question, I’m approaching Python since few days.
I’ve looked to some other threads and while I understand why this happens I’m not sure I have understood the possible solution.

I attach here a short example of code snippet:

class Class_one:
    name = "First"

class Class_two:
    new_object = Class_one()

instance_one = Class_two()
instance_one.new_object.name = "Second"
instance_two = Class_two()
instance_two.new_object.name = "Third"

print(instance_one.new_object.name)
print(instance_two.new_object.name)

I see that Class_one gets instantiated only one time despite I’m trying to have two different instances associated one with instance_one and the other with instance_two.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The objective would be to have "Second" and "Third" as results of the two print instructions, while I get "Third" and "Third".

What would be the proper way of getting that result, still preserving a two-classes structure?

>Solution :

The syntax you used is for class variables, meaning ones that are shared among instances of the same class. In order to declare instance variables, you need to do it referring to an instance, e.g. using the self paremeter of instance methods:

class Class_one:
    name = "First"

class Class_two:
    def __init__(self):
        self.new_object = Class_one()

instance_one = Class_two()
instance_one.new_object.name = "Second"
instance_two = Class_two()
instance_two.new_object.name = "Third"

print(instance_one.new_object.name)
print(instance_two.new_object.name)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading