I have to call extend on an object but then suddenly have to create a new Module and put my method in it.
Ruby's metaprogramming syntax is quite obscure sometimes.
Compare it with Python's, which I find more explicit and clear in this case:
importtypesclassPlayer:def__init__(self,name):self.name=namedefwalk(self):print(f"{self.name}: walking")defrun(self):print(f"{self.name}: running")defcreate_method(self,name,method):# set an attribute on this istance, with a name and the given methodsetattr(self,name,types.MethodType(method,self))mario=Player("mario")luigi=Player("luigi")mario.walk()luigi.run()deffly(self):print(f"{self.name}: fly like an eagle!")mario.create_method('fly',fly)mario.fly()luigi.fly()
the output:
mario: walking
luigi: running
mario: fly like an eagle!
Traceback (most recent call last):
File "t.py", line 29, in <module>
luigi.fly()
AttributeError: 'Player' object has no attribute 'fly'
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
@mudasobwa thanks for the addition!
Do you agree how weird is that syntax though?
I have to call
extend
on an object but then suddenly have to create a new Module and put my method in it.Ruby's metaprogramming syntax is quite obscure sometimes.
Compare it with Python's, which I find more explicit and clear in this case:
the output: