開発環境
- OS X El Capitan - Apple (OS)
- Emacs (Text Editor)
- Python 3.5 (プログラミング言語)
Introducing Python: Modern Computing in Simple Packages (Bill Lubanovic (著)、 O'Reilly Media)のChapter 6(Oh Oh: Objects and Classes)、Things to Do 6.1-10.を取り組んでみる。
Things to Do 6.1-10.
コード(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'
thing3 = Thing3()
print(thing3.letters)
print('6.4')
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol = symbol
self.number = number
def dump(self):
print('name: {0}, symbol: {1}, number: {2}'.format(
self.name, self.symbol, self.number))
def __str__(self):
return 'name: {0}, symbol: {1}, number: {2}'.format(
self.name, self.symbol, self.number)
hydrogen1 = Element('Hydrogen', 'H', 1)
print(hydrogen1)
print('6.5')
d = dict(name='Hydrogen', symbol='H', number=1)
hydrogen2 = Element(**d)
print(hydrogen2)
print('6.6')
hydrogen1.dump()
hydrogen2.dump()
print('6.7')
print(hydrogen1)
print(hydrogen2)
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.__name
def dump(self):
print('name: {0}, symbol: {1}, number: {2}'.format(
self.name, self.symbol, self.number))
def __str__(self):
return 'name: {0}, symbol: {1}, number: {2}'.format(
self.name, self.symbol, self.number)
h = Element('Hydrogen', 'H', 1)
print(h.name, h.symbol, h.number)
try:
print(h.__name)
except Exception as err:
print(err)
print(h._Element__name)
print('6.9')
class Bear:
def eats(self):
return 'berries'
class Rabbit:
def eats(self):
return 'clover'
class Octothorpe:
def eats(self):
return 'campers'
bear = Bear()
rabbit = Rabbit()
octothorpe = Octothorpe()
for a in [bear, rabbit, octothorpe]:
print(a.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 0x1052af208> 6.2 abc 6.3 xyz 6.4 name: Hydrogen, symbol: H, number: 1 6.5 name: Hydrogen, symbol: H, number: 1 6.6 name: Hydrogen, symbol: H, number: 1 name: Hydrogen, symbol: H, number: 1 6.7 name: Hydrogen, symbol: H, number: 1 name: Hydrogen, symbol: H, number: 1 6.8 Hydrogen H Hydrogen 'Element' object has no attribute '__name' Hydrogen 6.9 berries clover campers 6.10 disintegrate crush ring $
0 コメント:
コメントを投稿