jacobcan118
jacobcan118

Reputation: 9037

pass argument for instance variable for class

how can I pass argument for class's instance variable like following, how can I pass sclass for Subclass when I initial ClassElement

class Subclass(object):
    def __init__(self, arg):
        self.arg = arg


class ClassElement(object):
    sclass = Subclass('sclass')

    def __init__(self, argA: str, argB: str):
        self.argA = argA
        self.argB = argB
tcl = ClassElement('argA', 'argB')
print(tcl.argA)
print(tcl.argB)
print(tcl.sclass)
print(tcl.sclass.arg)

Upvotes: 0

Views: 80

Answers (2)

Chen A.
Chen A.

Reputation: 11280

Your code defines sclass as class variable, and you're checking an instance variable tcl.sclass.arg. These are two different things; class variables and instance variables.

If you want to use the same object to every instance - use class variable. If the object is unique to every instance - use instance variable.

Every instance has sclass:

class ClassElement(object):
    def __init__(self, argA, argB, sclass):
        self.argA = argA
        self.argB = argB
        self.sclass = Subclass(sclass)

All instances share single object (your code):

>>> ClassElement.sclass
<__main__.Subclass object at 0x02942BF0>
>>> ClassElement.sclass.arg
'sclass'

>>> tcl2 = ClassElement('argA', 'argB')
>>> id(tcl2.sclass)
43265008
>>> id(tcl.sclass)
43265008

Ok I think I understand now what you are looking for

class ClassElement(object):
    sclass = None

    def __init__(self, argA, argB, sclass):
        self.argA = argA
        self.argB = argB
        ClassElement.sclass = Subclass(sclass)

This will update the class variable with every instance creation.

Upvotes: 1

pstatix
pstatix

Reputation: 3848

class Subclass(object):
    def __init__(self, arg):
        self.arg = arg


class ClassElement(object):
    def __init__(self, argA, argB):
        self.argA = argA
        self.argB = argB
        self.sclass = Subclass('sclass')

tcl = ClassElement('argA', 'argB')

print(tcl.argA)
print(tcl.argB)
print(tcl.sclass)
print(tcl.sclass.arg)

Upvotes: 0

Related Questions