Skip to content
Advertisement

I have variables and values in __init__ method and I want to make a new dict in another method where the variable as key and values of it as value

I have this–

class A(object):
    def __init__(self):
        self.b = 1
        self.c = 2
        self.d = 4

I want —

class A(object):
    def __init__(self):
        self.b = 1
        self.c = 2
        self.d = 4

    def do_nothing(self):
        a={'b':1,'c':2,'d':4}

how to use instance variable as key value in another r method

Advertisement

Answer

Magic methods __dict__ can help you

class A(object):

    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3

    def test(self):
        print(self.__dict__)

a = A()
a.test()

Output

{'a': 1, 'b': 2, 'c': 3}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement