Python修改私有属性

Python修改私有属性教程

Python私有属性 只能在 内部访问,不能在类的外部调用,因此,我们需要修改 Python 的私有属性只能在类内部提供相应的 方法 来修改和获取。

我们可以在类内部,通过提供 get 和 set 方法来提供对类的私有属性的访问和修改,或者使用 gettersetter 装饰器提供对类私有属性的修改。

案例

Python类私有属性修改

使用类的实例方法,在类内部修改私有属性

print("嗨客网(www.haicoder.net)") class Person(object): def __init__(self, name, age, score): self.name = name self.age = age self.__score = score def setscore(self, val): self.__score = val def info(self): print("name =", person.name, "age =", person.age, "score =", person.__score) person = Person("haicoder", 18, 100) person.info() person.setscore(99) person.info()

程序运行后,控制台输出如下:

71_python类属性私有修改.png

我们定义了一个 Person 类,Person 类中有一个私有属性 __score,接着,我们提供了一个实例方法 setscore 实现对私有属性的修改。

最后,我们在类外部调用实例方法 setscore 成功的将私有属性 __score 的值修改为了 99。

使用 property 修改类私有属性

使用 property 实现在类的内部,修改类私有属性

print("嗨客网(www.haicoder.net)") class Person(object): def __init__(self, name, age, score): self.name = name self.age = age self.__score = score @property def score(self): return self.__score @score.setter def score(self, val): self.__score = val def info(self): print("name =", person.name, "age =", person.age, "score =", person.__score) person = Person("haicoder", 18, 100) person.info() person.score = 99 person.info()

程序运行后,控制台输出如下:

72_python类属性私有修改.png

我们在类 Person 中,使用了 getter 和 setter 装饰器,提供了类 Person 中私有属性 __score 的修改和获取的方法。

最后,我们在类外部调用装饰器方法成功的将私有属性 __score 的值修改为了 99。

Python修改私有属性总结

Python 的私有属性只能在类内部访问,不能在类的外部调用,因此,我们需要修改 Python 的私有属性只能在类内部提供相应的方法来修改和获取。

我们可以在类内部,通过提供 get 和 set 方法来提供对类的私有属性的访问和修改,或者使用 getter 和 setter 装饰器提供对类私有属性的修改。