LoginSignup
0
1

More than 3 years have passed since last update.

アクセス制限 と クラスを構造体として扱う事

Posted at
1
class T(object):
    pass

t1 = T()
t1.name = 'Mike'
t1.age = 20

print(t1.name, t1.age)
1の実行結果
Mike 20

この様に、
クラスをデータ構造体として扱う事は可能である。

しかし、
以下の様な場合は、注意が必要だ。

2
class Player:
    def __init__(self, job, weapon):
        self.job = job
        self.__weapon = weapon

    def walk(self):
        print(self.job + "は荒野を歩いていた")
        self.__attack("スライム")

    def __attack(self, enemy):
        print(self.__weapon + "で" + enemy + "を攻撃")


player1 = Player("戦士", "剣")
player1.__weapon = '斧'
print(player1.__weapon)
2の実行結果

本来、weaponはアクセス制限がかけられていて、
クラスの外からはアクセスできない様になっている。
なので、
print(player1.
weapon)はエラーとなるはずである。

しかしながら、
player1.weapon = '斧' で
新たに
weaponを生成してしまっている。

バグにつながる事があるので、
注意が必要である。

0
1
1

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
1