RubyãPythonã§åçãã£ã¹ããã/åçã¡ã½ããå®ç¾©
åçãã£ã¹ããã
åçãã£ã¹ãããã¯ããå®è¡æã«å¼ã³åºãã¡ã½ããã決ããããã¨ãæãã¾ãã
rubyã§ã¯sendã«ãã£ã¦åçãã£ã¹ããããã§ãã¾ã
method_to_call = :upcase obj = "abc" obj.send(method_to_call) # => "ABC"
pythonã§ã¯ã¡ã½ããããªãã¸ã§ã¯ããªã®ã§ãgetattrã使ã£ã¦ãã¡ã½ãããªãã¸ã§ã¯ããåå¾ãã¦ãå®è¡ãããã¨ãã§ãã¾ã
method_to_call = 'upper' obj = "abc" getattr(obj, method_to_call)() # => "ABC"
åçã¡ã½ããå®ç¾©
åçã¡ã½ããå®ç¾©ã¯ãå®è¡æã«ã¡ã½ãããå®ç¾©ããããã¨ãæãã¾ãã
rubyã§ã¯define_methodã使ç¨ãã¦åçã«ã¡ã½ãããå®ç¾©ãããã¨ãã§ãã¾ã
以ä¸ã¯è±èªçwikipediaã®rubyã®ãã¼ã¸ã«è¨è¼ããã¦ããä¾ã§ã
COLORS = { :black => "000", :red => "f00", :green => "0f0", :yellow => "ff0", :blue => "00f", :magenta => "f0f", :cyan => "0ff", :white => "fff" } class String COLORS.each do |color,code| define_method "in_#{color}" do "<span style=\"color: ##{code}\">#{self}</span>" end end end "Hello, World!".in_blue => "<span style=\"color: #00f\">Hello, World!</span>"
Stringã«ã¡ã½ãããåçã«è¿½å ãã¦ãã¾ããdefine_methodã使ããã¨ã«ãã£ã¦ãè¨è¿°éãæ¸ããã¦ãã¾ã
pythonã§ã¯ã¡ã½ããããªãã¸ã§ã¯ããªã®ã§ãsetattrã使ã£ã¦ãã¡ã½ãããªãã¸ã§ã¯ããã¯ã©ã¹ã«ã»ãããããã¨ãã§ãã¾ã
ãã ããã«ãã¤ã³ã¯ã©ã¹ã§ããstrã«ã¡ã½ããã追å ãããã¨ã¯ã§ãã¾ããã®ã§ãstrãç¶æ¿ããã¯ã©ã¹ãä½æããå¿
è¦ãããã¾ã
colours = {"black": "000", "red": "f00", "green": "0f0", "yellow": "ff0", "blue": "00f", "magenta": "f0f", "cyan": "0ff", "white": "fff"} class MyString(str): pass for name, code in colours.iteritems(): def _in_colour(self, code=code): return '<span style="color: #%s">%s</span>' % (code, self) setattr(MyString, "in_" + name, _in_colour) print MyString("Hello, world!").in_blue() # => <span style="color: #00f">Hello, world!</span>
åè)
Wikipedia(Ruby (programming language))
http://en.wikipedia.org/wiki/Ruby_%28programming_language%29
Python's equivalent for Ruby's define_method?
http://stackoverflow.com/questions/5449244/pythons-equivalent-for-rubys-define-method
RubyãPythonã§ã¯ã©ã¹ã®ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ããã追å ãã
http://d.hatena.ne.jp/yuheiomori0718/20120114/1326545228