Python @classmethodのcls

クラスメソッドの第1引数はclsで、クラス自身を示す

import datetime

class Reserve:

    dt_now = datetime.datetime.now()

    def __init__(self, dep, dest, time):
        self.dep = dep
        self.dest = dest
        self.time = time

    def plan(self):
        print(f"予約内容は、出発地:{self.dep}、目的地:{self.dest}、出発時間:{self.time}です")

    @classmethod
    def clock(cls):
        print(f"只今の時刻は、{cls.dt_now}です")


osakaTrip = Reserve("東京","大阪","16時")
osakaTrip.plan()
Reserve.clock()

$ python3 test.py
予約内容は、出発地:東京、目的地:大阪、出発時間:16時です
只今の時刻は、2023-11-16 02:47:03.822162です

print(f”只今の時刻は、{dt_now}です”) とすると、以下のようにエラーになります。
Traceback (most recent call last):
File “/home/vagrant/dev/test/test.py”, line 23, in
Reserve.clock()
File “/home/vagrant/dev/test/test.py”, line 18, in clock
print(f”只今の時刻は、{dt_now}です”)
NameError: name ‘dt_now’ is not defined

Pythonのhash関数

print(hash("abc"))
print(hash("def"))
print(hash(123))
print(hash(123.0))
print(hash(-123))
print(hash("abc"))

$ python3 test.py
-6216428559771217202
-5554558427243961036
123
123
-123
-6216428559771217202

Pythonのビッグ/リトルエンディアン

バイトを受け取り、リトルエンディアンとして解釈して数値を返す関数

def little_endian_to_int(b):

    return int.from_bytes(b, 'little')

数字を受け取り、リトルエンディアンとしてバイトを返却

def int_to_little_endian(n, length):

    return n.to_bytes(length, 'little')

バイト数も256とか指定するのではなく、引数lengthとして受け付ける。また、数字はiよりnの方がベター

pythonのdigest()とhexdigest()

digest()はバイト列、hexdigest()は16進数を返却する

import hashlib 

print(hashlib.sha256(b'test').digest())
print(hashlib.sha256(b'test').hexdigest())

$ python3 test.py
b’\x9f\x86\xd0\x81\x88L}e\x9a/\xea\xa0\xc5Z\xd0\x15\xa3\xbfO\x1b+\x0b\x82,\xd1]l\x15\xb0\xf0\n\x08′
9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08

pythonでdivmod

Pythonでは //で商、%で余りだが、divmodで両方を出力する。

q = 13 // 4
mod = 13 % 4
print(q, mod)

q, mod = divmod(17, 7)
print(q, mod)

$ python3 test.py
3 1
2 3

pythonのbytes型

bytesはバイナリデータを扱うバイト型

str1 = "高島屋"
enc_str1 = str1.encode()

print(f"{str1}:{enc_str1}")
print(f"type: {type(enc_str1)}")

print(f"高: {hex(ord('高'))}")
print(f"島: {hex(ord('島'))}")
print(f"屋: {hex(ord('屋'))}")

$ python3 test.py
高島屋:b’\xe9\xab\x98\xe5\xb3\xb6\xe5\xb1\x8b’
type:
高: 0x9ad8
島: 0x5cf6
屋: 0x5c4b

バイト型はb’で囲まれる
\xは続く文字列