0

I created a python class for example like:

class A():

    def foo(self):
        #Does something

def bar(self):
    #Does some work

A.bar = bar

According to my understanding this should add bar to the class. But when do this in a different class I get the mentioned error

global a

a=A()

a.bar() # this gives the error

Thanks.

Vivek Shankar
  • 770
  • 1
  • 15
  • 37
  • I know you can do this to an object, but to a class too? I'm not too positive about this. – dabadaba Mar 17 '17 at 13:13
  • @dabadaba Sorry for the late reply, apparently it can be done, please see [this](http://stackoverflow.com/questions/42856154/can-monkey-patching-replace-existing-function-definition-in-a-class/42857445#42857445) SO question and [this](https://www.codementor.io/jadianes/building-a-web-service-with-apache-spark-flask-example-app-part2-du1083854) tutorial I'm looking at. Also I have run and verified the code with the instance in the same class. – Vivek Shankar Mar 17 '17 at 18:28
  • but that's different, because the method with that name already exists. Apparently you cannot just assign `bar` (with a new behavior defined in an external function) to `A` if it is not defined. – dabadaba Mar 17 '17 at 18:37
  • @dabadaba I believe that is what monkeypatching is done for, also as I said in my previous comment the code doesn't give an error if everything is kept in the same file. – Vivek Shankar Mar 18 '17 at 14:15

1 Answers1

-1

Your bar function is outside the class. Correct it:

class A():

    def foo(self):
        print('foo')

    def bar(self):
        print('bar')

global a
a = A()
a.bar()
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Manpreet Ahluwalia
  • 301
  • 1
  • 3
  • 11