@property -->getter方法
@XX.setter -->setter方法
class User(object):
def __init__(self):
self.__username = None # 私有对象属性
self.__password = None # 私有对象属性
@property # getter
def username(self):
return self.__username
@username.setter # setter
def username(self,un):
if len(un) >= 6 and len(un) <= 18:
self.__username = un
else:
print("用户名%s不符合命名规定"%un)
@property # getter
def password(self):
return self.__password
@password.setter # setter
def password(self,pwd):
if len(pwd) >= 6 and len(pwd) <= 18:
self.__password = pwd
else:
print("密码%s不符合规定"%pwd)
if __name__ == "__main__":
my_user = User()
print("--使用@property升级setter和getter---")
my_user.username = 'zhangsan'
my_user.password = 'zs12345'
print(my_user.username)
print(my_user.password)
注意:1.因为python是一行一行读取代码,所以@property,@XX.setter有先后顺序之分。2.方法的名字是XX,getter方法和setter方法的名字必须相同。