1

I want to add a method to a class. This method contains 'self' which is referred to the class instance itself:

def func(self, t):
    return self.b + t

class A:
    pass

a = A()
a.b = 10 
a.foo = func
print(a.foo(3))

When I run the code above I get the error:

TypeError: func() missing 1 required positional argument: 't'

What's wrong with my code? Thanks!

user1403546
  • 1,680
  • 4
  • 22
  • 43
  • You *could* (not should) do `print(a.foo(a, 3))` but the question is why? What are you really trying to achieve? If this function should have access to the same instance's attribute why not making it a method to begin with? – DeepSpace Nov 16 '16 at 09:50
  • 1
    Possible duplicate of [Any elegant way to add a method to an existing object in python?](http://stackoverflow.com/questions/30294458/any-elegant-way-to-add-a-method-to-an-existing-object-in-python) – Zero Piraeus Nov 16 '16 at 09:54
  • thanks. I see that using partial package it works fine. @DeepSpace, what do you mean exactly? Is there a different way to declare methods when external to a class? – user1403546 Nov 17 '16 at 08:33
  • @user1403546 I mean that if `func` should always have access to `b` attribute of a class `A` instance then why not make it a method of `A`? – DeepSpace Nov 17 '16 at 08:36
  • Because I can't modify class A code. And since it's only a matter of one single function even declaring a class which inherited from A seemed too much – user1403546 Nov 17 '16 at 08:40

0 Answers0