目次
工作HardwareHubからのお知らせ
sample.py
#!/usr/bin/python
class MainClass:
x = 128
def setX(self, x):
self.x = x
def getX(self):
return self.x
class SubClass(MainClass):
def __init__(self):
self.x = 64
def display(self):
print self.x
obj = MainClass()
print obj.getX()
obj.setX(256)
print obj.getX()
obj = SubClass()
print obj.getX()
obj.setX(1024)
obj.display()
実行例
$ python sample.py
128
256
64
1024
with-as における処理を記述
enter と exit を実装することで with-as で利用できるクラスを実装できます。with 内で例外が発生した場合であっても __exit__
は実行されます。その場合、引数で例外の内容を取得できます。Java の try-with-resources や C# の using のようなものです。
main.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
class MyClass(object):
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
print "%r\n" % exc_type
print "%r\n" % exc_value
print "%r\n" % traceback
def Main():
with MyClass() as obj:
raise Exception("xxxx")
if __name__ == '__main__':
Main()
実行例
$ python main.py
<type 'exceptions.Exception'>
Exception('xxxx',)
<traceback object at 0x7fb9631a88c0>
Traceback (most recent call last):
File "main.py", line 17, in <module>
Main()
File "main.py", line 14, in Main
raise Exception("xxxx")
Exception: xxxx
その他
#!/usr/bin/python
# -*- coding: utf-8 -*-
# オブジェクトの属性値を取得
class MyClass(object):
x = 123
y = -123
obj = MyClass()
getattr(obj, 'x') # 123
# 静的メソッド化
class MyClass2(object):
@staticmethod
def f():
return 123
MyClass2.f() # 123
デストラクタ
class MyClass3(object):
def __del__(self):
print 'destructed'
def f():
obj = MyClass3()
f() # destructed
プロパティとしてメソッドを実行
@property
を用いると、プロパティのようにメソッドにアクセスできます。
#!/usr/bin/python
# -*- coding: utf-8 -*-
def Main():
obj = MyClass()
print(obj.myprop) #=> hi
class MyClass(object):
@property
def myprop(self):
return 'hi'
if __name__ == '__main__':
Main()
関連記事
- Python コードスニペット (条件分岐)if-elif-else sample.py #!/usr/bin/python # -*- coding: utf-8 -*- # コメント内であっても、ASCII外の文字が含まれる場合はエンコーディング情報が必須 x = 1 # 一行スタイル if x==0: print 'a' # 参考: and,or,notが使用可能 (&&,||はエラー) elif x==1: p...
- Python コードスニペット (リスト、タプル、ディクショナリ)リスト range 「0から10まで」といった範囲をリスト形式で生成します。 sample.py print range(10) # for(int i=0; i<10; ++i) ← C言語などのfor文と比較 print range(5,10) # for(int i=5; i<10; ++i) print range(5,10,2) # for(int i=5; i<10;...
- ZeroMQ (zmq) の Python サンプルコードZeroMQ を Python から利用する場合のサンプルコードを記載します。 Fixing the World To fix the world, we needed to do two things. One, to solve the general problem of "how to connect any code to any code, anywhere". Two, to wra...
- Matplotlib/SciPy/pandas/NumPy サンプルコードPython で数学的なことを試すときに利用される Matplotlib/SciPy/pandas/NumPy についてサンプルコードを記載します。 Matplotlib SciPy pandas [NumPy](https://www.numpy
- pytest の基本的な使い方pytest の基本的な使い方を記載します。 適宜参照するための公式ドキュメントページ Full pytest documentation API Reference インストール 適当なパッケージ