開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python (プログラミング言語)
Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART Ⅵ.(Classes and OOP)、CHAPTER 27(Class Coding Basics)、Test Your Knowledge: Quiz.1.~9.を解いてみる。
その他参考書籍
Test Your Knowledge: Quiz.1.~9.
コード(BBEdit)
sample.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
# tow key concepts
# __init__, self
class A:
x = 5 # class attribute
def __init__(self): # 最もよく使われるオーバーロード(constructor)
print('Hello, instance!')
def func(self): # selfはインスタンス自身を指す
print(self)
# +演算子をオーバーロード
# (本来はbuilt-in objectのように自然な演算を導入したい時に利用)
def __add__(self, other):
print('Hello, +!({})'.format(other))
A.y = 10 # class attribute
i1 = A()
i2 = A()
i1.z = 15 # instance attribute
print(i1.x, i1.y)
print(i2.x, i2.y)
try:
print(i2.z)
except Exception as err:
print(type(err), err, err.args)
try:
A.func()
except Exception as err:
print(type(err), err, err.args)
i1.func()
i2.func()
A.func(i1)
A.func(i2)
i1 + 10
i1 + 'python'
i1 + i2
i1 + A
入出力結果(Terminal)
$ ./sample.py
Hello, instance!
Hello, instance!
5 10
5 10
<class 'AttributeError'> 'A' object has no attribute 'z' ("'A' object has no attribute 'z'",)
<class 'TypeError'> func() missing 1 required positional argument: 'self' ("func() missing 1 required positional argument: 'self'",)
<__main__.A object at 0x10540fbd0>
<__main__.A object at 0x10540fcd0>
<__main__.A object at 0x10540fbd0>
<__main__.A object at 0x10540fcd0>
Hello, +!(10)
Hello, +!(python)
Hello, +!(<__main__.A object at 0x10540fcd0>)
Hello, +!(<class '__main__.A'>)
$
0 コメント:
コメントを投稿