Search code examples
pythonclassnestedinstance

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.

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)