Search code examples
pythonpython-3.xselfkeyword-argument

Need to use **kw in another method (not __init__)


So, I have a class with an init method who have as argument **kw. I need to use **kw in another method of the same class, but python return this error: AttributeError: 'MyClass' object has no attribute 'kw'

class MyClass:
    def __init__(self, **kw):
        if kw is not None:
            for value in kw.items():
                self.value = value

    def showdata(self):
        if self.kw is not None:
            for value in self.kw.items():
                print("value: " + value)

obj1 = MyClass(A = 237, B = 83, C = 182218)
print(obj1.showdata())

Maybe is there another way to do that? I've just started with OOP...


Solution

  • **kw (i.e. keyword arguments) is saved as a local variable in the __init__ function. What you need is to save it in the self argument to be an attribute of the class object.*

    Your code should first save **kw as an attribute, then use it in another function (method) in the class, since you are passing the self argument.

    class MyClass:
        def __init__(self, **kw):
            self.kw = kw
    
        def showdata(self):
            if self.kw:
                for key, value in self.kw.items():
                    print(key, ":", value)
    
    obj1 = MyClass(A = 237, B = 83, C = 182218)
    obj1.showdata()
    

    This code prints:

    A : 237
    B : 83
    C : 182218
    

    A few extra points:

    • for a dictionary, you can use if self.kw. If it is empty, it will not go through the if statement.
    • print("value" + value) only works if the variable value is of type str (string).
    • obj1.showdata() already has print inside it, so you do not have to print the output of the function, because it returns None.

    *self

    The self argument in Python refers to the current object. It has all the attributes of the object. That is why you can access **kw in another method of the class. I recommend this website if you are new to OOP in Python.