MPękalski
MPękalski

Reputation: 7103

New method to a class outside of the class definition

In Python, does anyone know of a nicer way of overriding a method of instantiated object that would give the function access to the class instance (self) and all its methods/properties?

The one below works, but somehow I do not like how use the global scope to pass object a to the new_f.

class A(object):
  def __init__(self):
    self.b = 10
  def f(self):
    return 2 + self.b
  def g(self):
    print(self.f())

a = A()

# simple override case
a.f = lambda: 10 
a.g()

# now I want to have access to property b of the object a
# but it also could be a method of object the object a
def new_f():
  self = a
  return 10+self.b

a.f = new_f
a.g()

Upvotes: 2

Views: 44

Answers (1)

TanMath
TanMath

Reputation: 608

One possible solution depending on your use case would be to define the function with self as an argument like def new_f(self) and then define A.f = new_f before initializing object a.

Upvotes: 2

Related Questions