python学习笔记(十三) 面向对象之访问控制,析构函数、重写函数、运算符重载

'''
析构函数:__del__() 释放对象是自动调用

'''

class person(object):

   #定义方法(定义函数)
   def run(self):
      print("run")
   def eat(self,food):
      print("eat " +food)
   def __init__(self,name,age,height,wight):
      # print(name,age,height,wight)
      self.name = name
      self.age= age
      self.height = height
      self.weight =wight
   def __del__(self):
      print("这里是析构函数")

per = person("sunck" ,22,170 ,77)
#释放对象
del per

#对象释放之后就不能再访问了
#print(per.age)

 

重写:

重写:将函数重新定义写一遍
__str()__:在调用print打印对象时自动调用,是给用户用的,是一个描述对象的方法

__rept()__:是给机器用的,在python解释器里面直接敲对象名再回车后调用的方法


访问控制:
#如果要让内部属性不被外部直接访问,在属性前加两个下划线(__),在
#python中如果在属性前加两个下划线,那么这个属性就变成了私有属性

#print(per.__money)  #外部使用
#per.run() #内部可以使用
class person(object):

	#定义方法(定义函数)
	def run(self):
		print("run")
	def eat(self,food):
		print("eat " +food)
	def __init__(self,name,age,height,wight,money):
		# print(name,age,height,wight)
		self.name = name
		self.age= age
		self.height = height
		self.weight =wight
		self.__money = money

	def setMoney(self,money):
		#数据过滤
		if money < 0:
			money = 0
		self.__money = money
	def getMoney(self):
		return self.__money

per =person("sunck" ,22,177,77,1000000)
# per.age=10
# print(per.age)

#如果要让内部属性不被外部直接访问,在属性前加两个下划线(__),在
#python中如果在属性前加两个下划线,那么这个属性就变成了私有属性

#print(per.__money)  #外部使用
#per.run() #内部可以使用

per.setMoney(100)
print(per.getMoney())

#不能直接访问per.__money是因为python解释器把__money变成了Person.__money

#在python中,__XXX__属于特殊变量,可以直接访问



 

运算符重载:




print(1 + 2)
print("1"+"2")
#不同的类型用加法会有不同的解释

class Person(object):
	def __init__(self,num):
		self.num=num
	#运算符重载
	def __add__(self, other):
		return Person(self.num + other.num)
	def __str__(self):
		return "num=" + str(self.num)

per1 = Person(1)
per2 = Person(2)
print(per1+per2)


'''''
3
12
num=3
'''''

重写:

重写:将函数重新定义写一遍
__str()__:在调用print打印对象时自动调用,是给用户用的,是一个描述对象的方法

__rept()__:是给机器用的,在python解释器里面直接敲对象名再回车后调用的方法
class person(object):

	#定义方法(定义函数)

	def __init__(self,name,age,height,wight):
		# print(name,age,height,wight)
		self.name = name
		self.age= age
		self.height = height
		self.weight =wight
	def __str__(self):
		#print("这里是str")
		return "%s-%d-%d-%d" %(self.name,self.age,self.height,self.weight)

per = person("sunck",20,170,66)
print(per)

#优点:当一个对象大的属性值很多,并且都需要打印时,用__str__很方便

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值