開発環境
- OS X El Capitan - Apple (OS)
- Emacs (Text Editor)
- Python 3.5 (プログラミング言語)
入門 Python 3 (Bill Lubanovic (著)、 斎藤 康毅(監修)、 長尾 高弘 (翻訳)、オライリージャパン)の6章(オブジェクトとクラス)、6.15(復習問題)を取り組んでみる。
コード(Emacs)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
print('6.1')
class Thing:
pass
print(Thing)
example = Thing()
print(example)
print('6.2')
class Thing2:
letters = 'abc'
print(Thing2.letters)
print('6.3')
class Thing3:
def __init__(self):
self.letters = 'xyz'
print(Thing3().letters)
print('6.4')
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol = symbol
self.number = number
elem = Element('Hydrogen', 'H', 1)
print(elem.name, elem.symbol, elem.number)
print('6.5')
d = dict(name='Hydrogen', symbol='H', number=1)
elem = Element(**d)
print(elem.name, elem.symbol, elem.number)
print('6.6')
class Element1(Element):
def dump(self):
print(self.name, self.symbol, self.number)
hydrogen = Element1('Hydrogen', 'H', 1)
hydrogen.dump()
print('6.7')
print(hydrogen)
class Element2(Element):
def __str__(self):
return 'name: {0}, symbol: {1}, number: {2}'.format(
self.name, self.symbol, self.number)
hydrogen = Element2('Hydrogen', 'H', 1)
print(hydrogen)
print('6.8')
class Element:
def __init__(self, name, symbol, number):
self.__name = name
self.__symbol = symbol
self.__number = number
@property
def name(self):
return self.__name
@property
def symbol(self):
return self.__symbol
@property
def number(self):
return self.__number
hydrogen = Element2('Hydrogen', 'H', 1)
print(hydrogen.name, hydrogen.symbol, hydrogen.number)
print('6.9')
class Bear:
def eats():
return 'berries'
class Rabbit:
def eats():
return 'clover'
class Octothorpe:
def eats():
return 'campers'
for cls in [Bear, Rabbit, Octothorpe]:
print(cls.eats())
print('6.10')
class Laser:
def does(self):
return 'disintegrate'
class Claw:
def does(self):
return 'crush'
class SmartPhone:
def does(self):
return 'ring'
class Robot:
def __init__(self):
self.laser = Laser()
self.claw = Claw()
self.smartPhone = SmartPhone()
def does(self):
for obj in [self.laser, self.claw, self.smartPhone]:
print(obj.does())
robot = Robot()
robot.does()
入出力結果(Terminal, IPython)
$ ./sample.py 6.1 <class '__main__.Thing'> <__main__.Thing object at 0x10fdbb080> 6.2 abc 6.3 xyz 6.4 Hydrogen H 1 6.5 Hydrogen H 1 6.6 Hydrogen H 1 6.7 <__main__.Element1 object at 0x10fdbb128> name: Hydrogen, symbol: H, number: 1 6.8 Hydrogen H 1 6.9 berries clover campers 6.10 disintegrate crush ring $
0 コメント:
コメントを投稿