''' 析构函数:__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__很方便