pythonbook/Python 基础教程/私有属性---封装.py

16 lines
427 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class Person:
def __init__(self, name, age):
self.name = name
self.__age = age
#定义对私有属性的get方法获取私有属性
def getAge(self):
return self.__age
#定义对私有属性的重新赋值的set方法重置私有属性
def setAge(self,age):
self.__age = age
person1 = Person("tom",19)
person1.setAge(20)
print(person1.name,person1.getAge()) #tom 20