0

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)
1
  • Your ClassElement has no attribute sclass Commented Nov 7, 2017 at 15:08

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

hi, yes, I would like to use SUbclass as class variable but passing 'sclass' as argument when initial ClassElement...is it possible
I've edited my answer; you can accept additional parameter on ClassElement, and then pass it to your SubClass as argument.
but your answer is using Subclass as instance variable not using as class variable and assign now arg for sclass
So you want it to be a class or instance variable? If it's a class, once you change it - it is changed for all instances
yes, i try to create one @classmethod to update it, it seems like without include on def __init__, but it does nto work after include in def init
0
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.