Python学习笔记 24

类里的特殊方法

垃圾回收:

这个只是简单了解,没有做深入研究

# 就像生活垃圾一样,程序在运行过程中也会产生垃圾
# 在程序中没有被引用的对象就是垃圾
# 垃圾回收就是将垃圾对象从内存中删除,python会自动删除垃圾,不用我们手动删除
class A:
	def __init__ (self):
		self.name = 'A类'

	def __del__(self):
	# 删除之前自动调用__del__方法
	 	print('A()被删除了、、',self)

a = A( )

# del a
a = None
# 此时没有任何变量对A( )对象的实例进行引用,A( )对象创建的实例就变成了垃圾

b = A( )
c = A( )
# print(b.name)

input('按回车键退出。。。')

# 程序结束时,对象也会被自动删除

特殊方法:

类里的特殊方法有太多了,并且都是大同小异,这里只是一部分:

__init__ , __del__ , __len__ , __str__ , __repr__ , __bool__ ,还有用于比较大小的,数学运算的

# 特殊方法使用__开头和结尾,
# 一般自动调用,不需要我们自己调用

# 已经学过的常用的有__init__ , __del__ , __len__

class Person:
	def __init__(self, name,age):
		self.name = name
		self.age = age

	# __str__特殊方法会在尝试将对象转换为字符串的时候调用
	# 它的作用可以用来指定对象转换为字符串的结果(print输出)
	def __str__(self):
		return 'Person [ name=%s ]'%self.name

	# __repr__特殊方法会在对当前对象使用repr( )函数时调用
	# 它的作用是指定对象在 "交互模式(IDLE,黑框))" 中直接输出的效果(直接输出)
	def __repr__(self):
		return '%s'%self.name

	# __len__()获取对象的长度

	# object.__bool__(self)
	# 可以通过bool来指定对象转换为bool值的情况
	def __bool__(self):
		return self.age>18

	# 比较大小的方法:
	# object.__lt__(self, other) <
	# object.__le__(self, other) <=
	# object.__eq__(self, other) ==
	# object.__ne__(self, other) !=
	# object.__gt__(self, other) >
	# object.__ge__(self, other) >=
	def __gt__(self, other):
		return self.age>other.age

	# 数学运算方法: (+, -, *, @, /, //, %, divmod(), pow(), **, <<, >>, &, ^, |)
	# object.__add__(self, other)
	# object.__sub__(self, other)
	# object.__mul__(self, other)
	# object.__matmul__(self, other)
	# object.__truediv__(self, other)
	# object.__floordiv__(self, other)
	# object.__mod__(self, other)
	# object.__divmod__(self, other)
	# object.__pow__(self, other[, modulo])
	# object.__lshift__(self, other)
	# object.__rshift__(self, other)
	# object.__and__(self, other)
	# object.__xor__(self, other)
	# object.__or__(self, other)


p1 = Person('小刘',17)
p2 = Person('老于',30)

print('__str__方法:',p1)# <__main__.Person object at 0x0310AE10>
# 执行print对象时,返回的就是特殊方法__str__的返回值

print('__repe__方法:',repr(p2))
print('__bool__方法:',bool(p1))
print('__gt__方法:',p1>p2)
print('__ne__方法:',p1!=p2)


猜你喜欢

转载自blog.csdn.net/weixin_44011689/article/details/89851941