首页 » 技术分享 » propety属性

propety属性

 

propety属性是吧方法当作属性来用,简化代码
proprty分为类方式和装饰器方式
类方式:

class  Acount(object):
	def __init__(self,name,blane):
		self.__name = name
		self.__blane = blane
		self.__age = age
	
	def get_name(self):
		return self.__name

	def get_blane(self):
		return self.__blane
	
	def set_blane(self,money):
		if isinstance(money,int):
			self.__blane += moey

	username = propety(get_name)
	blane = propety(get_blane,set_blane)

jack =Acount('jack',999)
print(jack.username)
print(jack.blane)	
jack.set_blane(1)
print(jack.blane)

属性方式

class Aocunt(object):
	def  __init__(self,blane,age):
		self.__blane = blane
		self.__age = age

	@propety
	def  get_blane(self):
		return self.__blane

	@blane.setter
	def set_blane(self,money):
		self.__blane += money

	@propety
	def get_age(self):
		return self.__age
		
	@age.setter
	def set_age(self,a):
		self.__age += a

jack = Aocunt(999,18)
print(jack.blane)
print(jack.age)
jack.age=2
jack.blane=1
print(jack.blane)
print(jack.age)

注意装饰器方式中@propety只能代替get方法,set方法需要用方法名.setter代替

转载自原文链接, 如需删除请联系管理员。

原文链接:propety属性,转载请注明来源!

0