Chao
Chao

Reputation: 3

Python Inner Class value assignment

I created a inner class within a class and created two instances of the class, but when assigning different values to the inner class properties, it is assigned to both instances. Can anyone help? Here's the code

class cl1:
    def __init__(self,tagName):
        self.name = tagName
    name1 = 'tagName'
    class cl2:
        name2 = 'name2'

test1 = cl1('test1')
test2 = cl1('test2')
test1.cl2.name2 = "cl1"
test2.cl2.name2 = 'cl2'
print (test1.cl2.name2)

When running it, the result is

cl2

Why it is not "cl1" as assigned?

Upvotes: 0

Views: 165

Answers (1)

CryptoFool
CryptoFool

Reputation: 23129

The value:

test1.cl2.name2

Is a class attribute for the class cl2. It is associated with that class, not with instances of that class. So even though you're going through references to an instance of the cl1 class to set the value of that attribute, since there is only one of them, the last thing you set it to wins. Your print statements are printing that same single value.

Google "python class vs instance variables" for a number of good looking write-ups of what the differences are between class and instance variables/attributes.

Here's an example that 1) Provides instance vs class atributes just where it seems you wanted them, and 2) renames the classes involved to have uppercase names so it's obvious when you're referencing an instance attribute vs a class attribute.

class Cl1:
    class Cl2:
        def __init__(self, tagName):
            self.name2 = tagName

    def __init__(self, tagName1, tagName2):
        self.name1 = tagName1
        self.cl2 = Cl1.Cl2(tagName2)

test1 = Cl1('test1', 'test2')
test2 = Cl1('test2', 'test2')
test1.cl2.name2 = 'cl1'
test2.cl2.name2 = 'cl2'
print(test1.cl2.name2)

Result:

cl1

Note that because you want to have an instance of the inner class associated with each instance of the outer class, the inner class's constructor has to instantiate an instance of the inner class as part of creating the outer class instance.

Also note the references to self. Instance variables are created inside a classes's constructor (its __init__ function) by referencing them on self, a reference to the instance being created.

Upvotes: 4

Related Questions