python3使用property简化getter和setter方法

property(getXX , setXX)

class User(object):
	def __init__(self):
		self.__username = None
		self.__password = None
	
	def setUsername(self,un):
		if len(un) >= 6 and len(un) <= 18:
			self.__username = un
		else:
			print("用户名%s不符合命名规定"%un)
	
	def getUsername(self):
		return self.__username 
	
	def setPassword(self,pwd):
		if len(pwd) >= 6 and len(pwd) <= 18:
			self.__password = pwd
		else:
			print("密码%s不符合规定"%pwd)
	
	def getPassword(self):
		return self.__password

	
	username = property(getUsername, setUsername)
	password = property(getPassword, setPassword)

if __name__ == "__main__":
	my_user = User()
	my_user.setUsername('asdfgh001')
	my_user.setPassword('a12345')
	print("--------getXX方法--------")
	print(my_user.getUsername())
	print(my_user.getPassword())
	print("--property升级setter和getter---")
	my_user.username = 'zhangsan'
	my_user.password = 'zs12345'
	print(my_user.username)
	print(my_user.password)

使用property简化getter和setter方法
username = property(getUsername, setUsername)
password = property(getPassword, setPassword)
方法调用时可以直接使用username = *** (setter)
python解释器会自动判断getter还是setter

你可能感兴趣的:(python学习)