Ruby
Ruby その1
code
# -*- coding: utf-8 -*- class Dog def initialize name, age @name = name @age = age end def name @name end def age @age end end class Breed < Dog def initialize name, age, breed super name, age @breed = breed @introduce = nil end def breed @breed end def introduce() @introduce = "#{@name} #{@age}歳、#{@breed}です。" end end taro = Dog.new("タロ", 6) p taro p taro.name hachi = Breed.new("ハチ", 10, "秋田犬") p hachi p hachi.name p hachi.age p hachi.breed p p hachi.introduce()
execution result
#<Dog:0x007fcd5304c0e0 @name="タロ", @age=6> "タロ" #<Breed:0x007fcd5304bf50 @name="ハチ", @age=10, @breed="秋田犬", @introduce=nil> "ハチ" 10 "秋田犬" "" "ハチ 10歳、秋田犬です。"
Rubyその2
code
# -*- coding: utf-8 -*- class Dog attr_accessor :name, :age def initialize name, age @name = name @age = age end end class Breed < Dog attr_accessor :name, :age, :breed def initialize name, age, breed super name, age @breed = breed @introduce = nil end def introduce() @introduce = "#{@name} #{@age}歳、#{@breed}です。" end end taro = Dog.new("タロ", 6) p taro p taro.name hachi = Breed.new("ハチ", 10, "秋田犬") p hachi p hachi.name p hachi.age p hachi.breed p "" p hachi.introduce()
execution result
#<Dog:0x007fe4f184ca50 @name="タロ", @age=6> "タロ" #<Breed:0x007fe4f184c8c0 @name="ハチ", @age=10, @breed="秋田犬", @introduce=nil> "ハチ" 10 "秋田犬" "" "ハチ 10歳、秋田犬です。"
Python
code
#!/usr/bin/env python # *-# -*- coding: utf-8 -*- class Dog(object): def __init__(self, name, age): self.name = name self.age = age class Breed(Dog): def __init__(self, name, age, breed): super(Breed, self).__init__(name, age) self.breed = breed def introduce(self): return "%(name)s %(age)s歳、%(breed)sです。" % \ {"name": self.name, "age": self.age, "breed": self.breed} taro = Dog("タロ", 6) print taro print taro.name hachi = Breed("ハチ", 10, "秋田犬") print hachi print hachi.name print hachi.age print hachi.breed print print hachi.introduce()
execution result
<__main__.Dog object at 0x10fd1ad10> タロ <__main__.Breed object at 0x10fd1ad50> ハチ 10 秋田犬 ハチ 10歳、秋田犬です。
メモ
- Pythonで『{"name": self.name}』とかコロンの後にスペース入れるのがPEP8的には正しいみたい。知らなかった(´・ω・`)
- http://oldriver.org/python/pep-0008j.html
*1:追加訂正:20120203