Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23247

Is it possible to add a function to a class at init if function uses a class attribute? [duplicate]

$
0
0

I have this script main.py:

class Test:    def __init__(self):                self.arg = 'argg!!!'    def meth_1(self , arg):                print(arg + self.arg)a = Test()a.meth_1('po')  # poargg!!!def meth_2(self, arg):    print(3 * arg + self.arg)Test.meth_1 = meth_2b = Test()b.meth_1('lo')  # lololoargg!!!class Test2:    def __init__(self):                self.arg = 'argg!!!'        self.meth_1 = meth_2c = Test2()c.meth_1('ho') # TypeError: meth_2() missing 1 required positional argument: 'arg'if def meth_2(self, arg):               # TypeError: meth_2() takes 1 positional argument but 2 were given if def meth_2(arg):

Is there any way to add a function to a class as method at __init__ making it access class attributes? That is, in my case, have c.meth_1('ho') working? If not, why?


Viewing all articles
Browse latest Browse all 23247

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>