obj = SomeObject.new def obj.new_method "do some things" end puts obj.new_method > "do some things"
This works ok. However, I need to do same thing inside an existing method:
def some_random_method def obj.new_method "do some things" end end
Works ok as well, but having a method inside a method looks pretty horrible. The question is, is there any alternate way of adding such a method?
The __add__() method in Python specifies what happens when you call + on two objects. When you call obj1 + obj2, you are essentially calling obj1. __add__(obj2). This works, because int implements the __add__() method behind the scenes.
Yes, it is possible - But not recommended Don't do it. Here's a couple of reasons: You'll add a bound object to every instance you do this to. If you do this a lot, you'll probably waste a lot of memory.
The normal way to add functionality (methods) to a class in Python is to define functions in the class body. There are many other ways to accomplish this that can be useful in different situations. The method can also be defined outside the scope of the class.
Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.
In ruby 1.9+, there's a better way of doing this using define_singleton_method
, as follows:
obj = SomeObject.new obj.define_singleton_method(:new_method) do "do some things" end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With