読者です 読者をやめる 読者になる 読者になる

Studio3104::BLOG.new

uninitialized constant Studio3104 (NameError)

Python でオブジェクト内部の dict に直接アクセスする

  • Ruby でいうとこのこういうやつ。
class Hage
  def initialize()
    @hage = { bozu: 1, hage: 2 }
  end

  def [](key)
    @hage[key]
  end

  def []=(key, value)
    @hage[key] = value
  end
end

h = Hage.new()
p h                    #=> #<Hage:0x007f94428a2c20 @hage={:bozu=>1, :hage=>2}>
p h[:bozu]         #=> 1
h[:fusa] = 3
p h[:fusa]          #=> 3
  • Python でやるとこう。
class Hage:
    def __init__(self):
        self.hage = { 'bozu': 1, 'hage': 2 }

    def __getitem__(self, key):
        return self.hage[key]

    def __setitem__(self, key, value):
        self.hage[key] = value

h = Hage()
print h            #=> <__main__.Hage instance at 0x109f6aef0>
print h['hage'] #=> 2
h['fusa'] = 3
print h['fusa']  #=> 3

thank you for letting me, @!