Cat Tom = new Cat() { @Override public String say() { return "Meau! Meau! MEAU!!!"; } }; 

This is code from java. Is it possible to crank such a feature on a python and expose not a class method but a specific object to polymorphism, and how?

  • one
    There is no polymorphism at the object level. In this example, a new anonymous (nameless) class is implicitly created. - user194374

2 answers 2

This is such a short derivative class entry with one method overlapped.

On Python, simply create a derived class and override the method manually. (In Python, as in Java, class methods are essentially virtual.)

    Python and Java - different languages ​​and approaches to solving the same problem may differ. In this case, you can use the fact that in Python every object can change (almost) any property, including redefining the class methods:

     class Test: def say(self): print("class Test") test = Test() test2 = Test() test2.say = lambda: print("test2") test.say() test2.say() 

    The output of this program:

    class Test

    test2

    • one
      Wow, cool, did not know. - VladD