1. 程式人生 > 實用技巧 >python 私有屬性的作用

python 私有屬性的作用

python 私有屬性的作用

class Player():
    def __init__(self, name, power, skill):
        self.name = name
        self.power = power
        self.skill = skill

    def print_role(self):
        print(('%s: %s %s')%(self.name,self.power,self.skill))

    def updateName(self, new_name):
        self.name 
= new_name user1 = Player('tom',100,'police') user1.print_role() #tom: 100 police user1.updateName('jack') # 可以更新名字 user1.print_role() #jack: 100 police user1.name = 'mark' # 可以更新名字 user1.print_role() #mark: 100 police

當屬性變成私有屬性之後,只能通過方法來更改屬性值,避免了屬性直接被強制修改

class Player():
    def __init__(self, name, power, skill):
        self.__name = name
        self.power = power
        self.skill = skill

    def print_role(self):
        print(('%s: %s %s')%(self.__name,self.power,self.skill))

    def updateName(self, new_name):
        self.__name = new_name

user1 
= Player('tom',100,'police') user1.print_role() #tom: 100 police user1.updateName('jack') #可以更新名字 user1.print_role() #jack: 100 police user1.__name = 'lili' #無法更新名字 user1.print_role() #jack: 100 police user1.name = 'mark' #無法更新名字 user1.print_role() #jack: 100 police

python 私有屬性的作用