If you define a method in a Ruby class and define a method in it, it becomes a method of the original class.

I was a little surprised, so I will write a code piece and a brief explanation.

sample.rb


class A
  def a1
    def a2
      'a2'
    end
    'a1'
  end
end

output1


irb(main):013:0> obj1 = A.new
=> #<A:0x00000002500198>
irb(main):014:0> obj1.a1
=> "a1"
irb(main):015:0> obj1.a2
=> "a2"

As you can see, the call to a1 dynamically defines a2 as an instance method of A. By the way, a2 does not exist unless a1 is called.

output2


irb(main):009:0> obj2 = A.new
=> #<A:0x000000011b7398>
irb(main):010:0> obj2.a2
NoMethodError: undefined method `a2' for #<A:0x000000011b7398>
        from (irb):10
        from /usr/bin/irb:11:in `<main>'

Since a2 is defined as an instance method of A (because it is commonly referenced by an instance of A), it can be called on all objects until the program terminates or is explicitly removed from A.

output3


irb(main):009:0> obj3 = A.new
=> #<A:0x00000001106f70>
irb(main):010:0> obj3.a1
=> "a1"
irb(main):011:0> obj3.a2
=> "a2"
irb(main):012:0> obj4 = A.new
=> #<A:0x00000001118888>
irb(main):013:0> obj4.a2
=> "a2"

By the way, this story can be found in Metaprogramming Ruby 2nd Edition, p111.

Would it be like doing the same thing with python?

sample.py


class A:
  def a1(self):
    self.__class__.a2 = lambda cls: 'a2'
    return 'a1'

output4


>>> obj1 = A()
>>> obj1.a1()
'a1'
>>> obj1.a2()
'a2'
>>> obj2 = A()
>>> obj2.a2()
'a2'

If this is the case, I still feel like I'm doing it forcibly and it's safe (?).

Recommended Posts

If you define a method in a Ruby class and define a method in it, it becomes a method of the original class.
If you want a singleton in python, think of the module as a singleton
You can call the method of the class directly in Python3 without adding @staticmethod
If you guys in the scope kitchen can do it with a margin ~ ♪
Define a division value in Django and easily reflect it on the screen
[Python] Wouldn't it be the best and highest if you could grasp the characteristics of a company with nlplot?
The result of making a map album of Italy honeymoon in Python and sharing it
How to use the __call__ method in a Python class
If you want to put an argument in the closure function and execute it later
Scraping the schedule of Hinatazaka46 and reflecting it in Google Calendar
What to do if you grep a text file and it becomes Binary file (standard input) matches
Delete a particular character in Python if it is the last
If you give a list with the default argument of the function ...
A function that measures the processing time of a method in python
[Python] The role of the asterisk in front of the variable. Divide the input value and assign it to a variable
I want to clear up the question of the "__init__" method and the "self" argument of a Python class.
[Python / Jupyter] Translate the comment of the program copied to the clipboard and insert it in a new cell
If you want to switch the execution user in the middle of a Fabric task, settings context manager
Predict the amount of electricity used in 2 days and publish it in CSV
Until you get a snapshot of Amazon Elasticsearch service and restore it
Enclose the cat result in double quotes and put it in a variable
Hit a method of a class instance with the Python Bottle Web API
If you get a no attribute error in boto3, check the version
Find it in the procession and edit it
What I investigated in the process of expressing (schematicizing) containers in a nested frame with Jupyter and making it
A simple mock server that simply embeds the HTTP request header in the body of the response and returns it.
How to save the feature point information of an image in a file and use it for matching
Create a simple app that incorporates the Fetch API of Ajax requests in Flask and explain it quickly
A solution if you accidentally remove the python interpreter in / usr / local / bin /.
I compared the speed of regular expressions in Ruby, Python, and Perl (2013 version)
Divides the character string by the specified number of characters. In Ruby and Python.
How to count the number of elements in Django and output to a template
In Python, change the behavior of the method depending on how it is called
Test the number of times you have thrown a query (sql) in django
You walk in a spiral in a world where the walls of the cross rise (simulation)
I didn't have to write a decorator in the class Thank you contextmanager
Until you get daily data for multiple years of Japanese stocks and save it in a single CSV (Python)
Get the caller of a function in Python
Specifying the range of ruby and python arrays
I wrote a class in Python3 and Java
Make a copy of the list in Python
Find the number of days in a month
Even if you are a beginner in python and have less than a year of horse racing, you could win a triple.
Output in the form of a python array
In bash, "Delete the file if it exists".
A discussion of the strengths and weaknesses of Python
[Python3] Take a screenshot of a web page on the server and crop it further
What happens if you graph the number of views and ratings/comments of the video of "Flag-chan!" [Python] [Graph]
[Python] Change the text color and background color of a specific keyword in print output
[Selenium] Open the link in a new tab and move it [Python / Chrome Driver]
[Shell art] Only when it is a multiple of 3 and a number with 3 becomes stupid
How to check in Python if one of the elements of a list is in another list
Understand Python yield If you put yield in a function, it will change to a generator
If you are interested in data scientists, first look around here, a summary of literature and videos (added as needed)
Check if the string is a number in python
Difference between Ruby and Python in terms of variables
Read the csv file and display it in the browser
A python implementation of the Bayesian linear regression class
Check if it is Unix in the scripting language
A shell program that becomes aho in multiples of 3
If you encounter a "Unicode Decode Error" in Python