Python super().__init__()の使い方

継承元のコンストラクタをオーバラーライドする

class Parent:
    def __init__(self, a, b):
        self.a = a 
        self.b = b
    
    def w(self):
        print(self.b)

class Child(Parent):
    def w(self):
        return super().w()

child = Child(0, 'hello')
child.w()

サブクラスで__init__を定義すると親クラスの上書きされてしまう。

class A:
    def __init__(self, name):
        self.name = name 

class B(A):
    def __init__(self, name, mail):
        super().__init__(name)
        self.mail = mail

b = B("yamada", "gmail")
b.name
class Parent:
    def __init__(self, name, age):
        self.name = name 
        self.age = age 

    def my_name(self):
        print("名前は" + self.name + "。年齢は" + str(self.age) + "歳。")

class Child(Parent):
    def __init__(self, name, age):
        super().__init__(name, age)

yamada = Child("yamada", 20)
yamada.my_name()

Python unittestのTextTestRunner().runを理解する

$ sudo apt install tree
$ tree
.
├── other.py
├── suite.py
└── test.py

test.py

import unittest

class MyTest(unittest.TestCase):
    def test_mytest_01(self):
        print("test_mytest_01 is called")
        one = 1
        self.assertEqual(one, 1, "one is 1")

other.py

import unittest

class OhterTest(unittest.TestCase):
    def test_other_01(self):
        print("test_mytest_01 is called")
        two = 2
        self.assertEqual(two, 2, "two is 2")

suite.py

import unittest

import test
import other

def suite():
    test_suite = unittest.TestSuite()
    test_suite.addTest(unittest.makeSuite(test.MyTest))
    test_suite.addTest(unittest.makeSuite(other.OhterTest))
    return test_suite

if __name__ == "__main__":
    mySuite = suite()
    unittest.TextTestRunner().run(mySuite)

$ python3 suite.py
test_mytest_01 is called
.test_mytest_01 is called
.
———————————————————————-
Ran 2 tests in 0.000s

OK

addTestとして、unittest.TextTestRunner().run() でテストを実行する

Pythonでunittest

unittestモジュールをimportし、unittest.TestCaseクラスを継承したテストクラスを作成する。その際、テストメソッドはtestという単語で始まる必要がある。

import uittest
from my_module import my_function

class MyTest(unittest.TestCase):
    def test_my_function(self):
        result = my_function(2)
        self.assertEqual(result, 4)

if __name__ == '__main__':
    unittest.main()

具体例

import unittest

def add(a, b):
    return a + b

class TestAddFunction(unittest.TestCase):

    def test_add_integer(self):
        result = add(2, 3)
        self.assertEqual(result, 5)

    def test_add_floats(self):
        result = add(2.5, 3.5)
        self.assertAlmostEqual(result, 6.0, places=2)

    def test_add_strings(self):
        result = add("Hello, ", "world!")
        self.assertEqual(result, "Hello, world!")

if __name__ == '__main__':
    unittest.main()

$ python3 test.py

———————————————————————-
Ran 3 tests in 0.000s

OK

return a + b + 1 とすると、
$ python3 test.py
FFE
======================================================================
ERROR: test_add_strings (__main__.TestAddFunction)
———————————————————————-
Traceback (most recent call last):
File “/home/vagrant/dev/blockchain/test.py”, line 17, in test_add_strings
result = add(“Hello, “, “world!”)
File “/home/vagrant/dev/blockchain/test.py”, line 4, in add
return a + b + 1
TypeError: can only concatenate str (not “int”) to str

======================================================================
FAIL: test_add_floats (__main__.TestAddFunction)
———————————————————————-
Traceback (most recent call last):
File “/home/vagrant/dev/blockchain/test.py”, line 14, in test_add_floats
self.assertAlmostEqual(result, 6.0, places=2)
AssertionError: 7.0 != 6.0 within 2 places (1.0 difference)

======================================================================
FAIL: test_add_integer (__main__.TestAddFunction)
———————————————————————-
Traceback (most recent call last):
File “/home/vagrant/dev/blockchain/test.py”, line 10, in test_add_integer
self.assertEqual(result, 5)
AssertionError: 6 != 5

———————————————————————-
Ran 3 tests in 0.000s

FAILED (failures=2, errors=1)

Test Classの中で、setUp, tearDownを入れると、テストの実行前後でそれぞれ実行される。

class TestAddFunction(unittest.TestCase):

    def setUp(self):
        print("setUp() called")

    def test_add_integer(self):
        result = add(2, 3)
        self.assertEqual(result, 5)

    def test_add_floats(self):
        result = add(2.5, 3.5)
        self.assertAlmostEqual(result, 6.0, places=2)

    def test_add_strings(self):
        result = add("Hello, ", "world!")
        self.assertEqual(result, "Hello, world!")

    def tearDown(self):
        print("tearDown() called")

pythonのpow

pow(self.nom, exponent, self.prime)で計算できる

prime = 7
for i in range(1, prime):
    a = pow(i, prime-1, 6)
    print(a)
for prime in (7, 11, 17 , 31):
    for i in range(1, prime):
        a = pow(i, prime-1, 6)
        print(a)
for prime in (7, 11, 17 , 31):
    print([pow(i, prime-1, prime) for i in range(1, prime)])

$ python3 test.py
[1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

3/24 のF31は

prime = 31
a = 3 * pow(24, prime-2)
print(a % prime)

print(pow(17, -3, prime))

print(pow(4, -4, prime)*11 % prime)

Pythonのtype()と__class__

type() は、オブジェクトのタイプまたはクラスを見つけるために使用できる事前定義された関数
__name__ は、基本的にそれが使用されている現在のモジュールの名前を与える特別な組み込み変数

class Num:
    def __init__(self, num):
        self.num = num

x = Num(1)
print(type(x).__name__)

$ python3 test.py
Num

__class__ プロパティを使用して、オブジェクトのクラスまたはタイプを検索することもできる。これは基本的に、オブジェクトが作成されたクラスを指す。

class Num:
    def __init__(self, num):
        self.num = num

x = Num(1)
print(x.__class__)
print(x.__class__.__name__)

$ python3 test.py

Num

Pythonのraise ValueError

関数などで例外を発生させたい場合にraiseを使用する。

raise 例外クラス(message):

def process_list(numbers):
    for num in numbers:
        try:
            if num < 0:
                raise ValueError("Negative numbers are not allowed.")
            result = 100 / num
            print(f"Result of division: {result}")
        except ZeroDivisionError:
            print("Error: Division by zero is not allowed.")
        except ValueError as ve:
            print(f"Error: {ve}")
        except Exception as e:
            print(f"Error occurred: {e}")

Pythonの__rpr__メソッド

__str__, __repr__は特殊メソッドと呼ぶ

initのみの場合

class Person:

    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age

mike = Person('Mike', 20)
print(mike)
class Person:

    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age

mike = Person('Mike', 20)
print(f'name: {mike.name}, age: {mike.age}')

classの中に書く

class Person:

    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age

    def __str__(self) -> str:
        return f'name: {mike.name}, age: {mike.age}'

mike = Person('Mike', 20)
print(mike)

__repr__ は同じ値のオブジェクトを再生成できる文字列を定義。

class Person:

    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age

    def __repr__(self) -> str:
        return f'name: {mike.name}, age: {mike.age}'

mike = Person('Mike', 20)
print(repr(mike))
class Person:

    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age

    def __repr__(self) -> str:
        return f'name: {mike.name}, age: {mike.age}'

mike = Person('Mike', 20)
print(repr(mike))

16進数と整数の変換

0xはその文字列が16進数であることを示す

print(format(0xabcd, 'x'))
print(hex(0xabcd))
print('%02x' % 0xabcd)

binasciiはバイト列に変換する

import binascii
print(binascii.unhexlify('abcd'))
print(str(binascii.hexlify(b'\xab\xcd'), 'utf-8'))

python基礎

bit演算子

print(bin(10))
print(bin(13))
print(bin(10|13))
print(bin(10))
print(bin(13))
print(bin(10&13))

シフト演算

print(bin(15))
print(bin(15<<0))
print(bin(15<<1))
print(bin(15<<2))
print(bin(15<<3))
print(bin(15<<4))

print(bin(15))
print(bin(15>>0))
print(bin(15>>1))
print(bin(15>>2))
print(bin(15>>3))
print(bin(15>>4))

list

list2=[10,20,30]
list2.append(40)
print(list2)

list3=[1,2,3,4,5]
list3.insert(3, 10)
print(list3)

list4=[1,2,3,4,5]
print(len(list4))

dictionary

dic1 = {"A": 1, "B": 2}
dic2 = {}
dic2["key"] = "value"

print(dic1)
print(dic2)

class, instance

class Greet():
    def __init__(self, greet):
        self.value = greet

morning = Greet("おはよう!")
evening = Greet("こんばんわ!")

print(morning.value)
print(evening.value)

__str__(self)は自動的に文字出力する

class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return "Name:" + self.name + ", Age:" + str(self.age)

satoshi = Person("satoshi", 30)
print(satoshi)

import

import numpy as np

def area_circle(r):
    ans = np.pi * r **2
    return ans 
print(area_circle(3))

これをfromを使って以下のように書くことができる。コードを省略できるメリットがある。

from numpy import pi

def area_circle(r):
    ans = pi * r **2
    return ans 
print(area_circle(3))

【Python】listのappend

appendとすると、リストの最後に追加される

names = ["Alice", "Bob", "Charlie"]

names.append("Dave")
print(names)

$ python3 test.py
[‘Alice’, ‘Bob’, ‘Charlie’, ‘Dave’]

カッコで囲んで二つ入れると

names = [(“Alice”,”20″), (“Bob”,”23″), (“Charlie”,”25″)]

names.append((“Dave”,”12″))
print(names)
print(names[0][1])
[/code]
基本的に一つしか入らないがタプルとして入れることもできる
$ python3 test.py
[(‘Alice’, ’20’), (‘Bob’, ’23’), (‘Charlie’, ’25’), (‘Dave’, ’12’)]
20