コスギデンサン >> 情報系メモ >> Python

Python : オブジェクトを引数として渡す Version 3.6.1 on CentOS7 2017/5

引数として渡すクラスオブジェクトがポインタかどうかを確かめる。
#
# 値を保持するだけのクラス
#
class Arg:
    count = 0

#
# テストクラス
#
class Test:
    def __init__(self, a, n):
        self.arg = a
        self.name = n

    def AddCount(self):
        self.arg.count = self.arg.count + 1

    def PrintCount(self):
        print(self.name + " : " + str(self.arg.count));

#main
a = Arg()

t1 = Test(a, "test1")
t2 = Test(a, "test2")

t1.AddCount()
t1.PrintCount()
t2.PrintCount()

t2.AddCount()
t1.PrintCount()
t2.PrintCount()
実行結果
test1 : 1
test2 : 1
test1 : 2
test2 : 2

ばらして別ファイルにしてみる
arg_class.py
#
# 値を保持するだけのクラス
#
class Arg:
    count = 0
test_class.py
#
# テストクラス
#
class Test:
    def __init__(self, a, n):
        self.arg = a
        self.name = n

    def AddCount(self):
        self.arg.count = self.arg.count + 1

    def PrintCount(self):
        print(self.name + " : " + str(self.arg.count));
test_main.py
import arg_class
import test_class

# main
a = arg_class.Arg()

t1 = test_class.Test(a, "test1")
t2 = test_class.Test(a, "test2")

t1.AddCount()
t1.PrintCount()
t2.PrintCount()

t2.AddCount()
t1.PrintCount()
t2.PrintCount()
実行結果
$ python test_main.py
test1 : 1
test2 : 1
test1 : 2
test2 : 2