简体   繁体   中英

How to inherit from class to modify one of their methods in Python?

I have this Python code:

class Parent(object):
    def __init__(self):
        self.value = 5

    def get_value(self):
        return self.value

Now I must modify the get_value method, and I did this:

class Child(Parent):
    def get_value(self):
        return self.value + 1

As expected, I get this result:

>>> p = Parent()
>>> p.get_value()
5

>>> c = Child()
>>> c.get_value()
6

But I need to get this result:

>>> p = Parent()
>>> p.get_value()
6

In other words, I need to modify the get_value method of Parent class without touching the source code. I've been programming such a long time only in Odoo framework (made with Python 2.7) that I've forgotten things like this, may be this question is duplicated, but I still haven't found a solution.

Can anyone help me, please?

Perhaps this is what you're looking for:

class MyClass:
  def MyFunc(self):
    return 3

def newFunc(self):
    return 4

# set the function equal to the new function
MyClass.MyFunc = newFunc

b = MyClass()

# normally would print 3, but prints 4 due to newFunc(self)
print(b.MyFunc())

I'm not really sure why you would want to do this though. If someone else works on a part of your code and needs to access MyClass.MyFunc() without noticing you've changed it's behavior, it will give them unexpected results.

It may be better to write a child class that does what you want it to do instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM