LoginSignup
0
0

More than 1 year has passed since last update.

Pythonで複数のclassごとにIDを振る方法

Posted at

やりたいこと

製品A,Bのオブジェクトがそれぞれいくつかあって、A,BごとにIDを1から振りたいという場合の方法です。クラス変数を置いて、インスタンスを作るごとにクラス変数に1を足す方法はいろんな方が書かれていたのですが、それを継承させる方法が見つからなかったので、備忘として書いておきます。

やり方

まず、元となるクラス(BaseProduct)を作り、それをA,Bの各クラスに継承させます。元クラスにはクラス変数(class_count)を作り、クラスごとのID(class_id)にそれを入れて、入れ終わったら1を足す、というメソッドをクラスメソッドとして定義します。
その後、インスタンス変数としてのidにclass_idを入れてやるという処理です。見ていただいが方が早いですね。

class BaseProduct:
    class_count = 1
    @classmethod
    def id_counter(cls):
        cls.class_id = cls.class_count
        cls.class_count += 1
        
    def __init__(self):
        self.id_counter()
        self.id = self.class_id


class ProductA(BaseProduct):
    def __init__(self):
        super().__init__()

class ProductB(BaseProduct):
    def __init__(self):
        super().__init__()

参考サイト

クラス変数の付け方、呼び出し方はこちらのサイトを参考にさせていただきました。ありがとうございました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0