概述
repr
定制对象显示规则
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
stu = Student('wyb', 23)
print(stu)
print(stu.__repr__())
输出:
<main.Student object at 0x0000026C9D9EB5C8>
<main.Student object at 0x0000026C9D9EB5C8>
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return 'Student[name=' + self.name + ',age=' + str(self.age) + ']'
stu = Student('wyb', 23)
print(stu)
print(stu.__repr__())
输出:
Student[name=wyb,age=23]
Student[name=wyb,age=23]
del
定制对象的析构方法,常用在手动释放外部资源的情况。
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
self.f = open('adult-all.csv')
def __del__(self):
print('析构')
self.f.close()
stu = Student('wyb', 23)
a = stu # 引用次数不为零, del stu先不执行
del stu
print('***********')
'''
输出:
***********
析构
'''
new
创建类的实例
init:负责初始化类的实例
class Student:
def __new__(cls, *args, **kwargs): # 创建类的实例
print('new()方法')
def __init__(self): # 初始化类的实例,实例由new方法传递过来,即self。没有传递,所以init没被调用
print('init()方法')
stu = Student()
'''
输出:
new()方法
'''
class Student:
def __new__(cls, *args, **kwargs): # 创建类的实例
print('new()方法')
return object.__new__(cls) # 调用init
def __init__(self): # 初始化类的实例,实例由new方法传递过来,即self。
print('init()方法')
stu = Student()
'''
输出:
new()方法
init()方法
'''
class newint(int):
def __new__(cls, value):
print('new...')
return int.__new__(cls, abs(value))
a = newint(-4.3)
print(a)
输出:
new…
4
实现类的单例模式
class Student:
def __init__(self, name): # 初始化类的实例,实例由new方法传递过来,即self。
print('init()方法,{}'.format(name))
stu1 = Student('zhangsan')
stu2 = Student('zhang')
print(stu1)
print(stu2)
'''
输出:
init()方法,zhangsan
init()方法,zhang
<__main__.Student object at 0x000001DE1223B388>
<__main__.Student object at 0x000001DE1223B488>
'''
↑没有实现单例,↓实现了单例
class Student:
__isInstance = False # 保存已经创建好的实例
def __new__(cls, *args, **kwargs):
#没有,则创建
if not cls.__isInstance:
cls.__isInstance = object.__new__(cls)
#有,则直接返回
return cls.__isInstance
def __init__(self, name): # 初始化类的实例,实例由new方法传递过来,即self。
print('init()方法,{}'.format(name))
stu1 = Student('zhangsan')
stu2 = Student('zhang')
print(stu1)
print(stu2)
'''
输出:
init()方法,zhangsan
init()方法,zhang
<__main__.Student object at 0x000002219136B888>
<__main__.Student object at 0x000002219136B888>
'''
属性管理
注意类属性和实例属性的区别。
可以动态添加实例属性,每个对象都不同。
getatrribute
访问不存在的属性的异常处理方法一:
可实现控制台日志输出的功能:
设置某些属性的访问控制权限:
在__getatrribute__方法中判断
getattr
处理异常,访问不存在的属性时候被调用,访问不存在的属性的异常处理方法二。
class Student:
address = 'china' # 类属性
def __init__(self, name, age): # 实例属性
self.name = name
self.age = age
def __getattr__(self, item):
print('getattr方法调用{}'.format(item))
stu = Student('zhang', 19)
print(stu.xxx)
'''
输出:
getattr方法调用xxx
None
'''
setattr
class Student:
def __init__(self, name, age): # 实例属性
self.name = name
self.age = age
def __setattr__(self, key, value):
if key == 'age':
if value < 18:
raise Exception('age<18')
else:
self.__dict__['age'] = value
#self.age = value #不可以这么写。死循环,因为又调用了__setattr__
stu = Student('zhang', 9)
'''
输出:
Traceback (most recent call last):
...
Exception: age<18
'''
反射
- 动态调用对应方法:hasattr
class Dog:
def __init__(self, name): # 实例属性
self.name = name
def eat(self):
print('{} eat'.format(self.name))
def sleep(self):
print('{} sleep'.format(self.name))
dog = Dog('erha')
choice = input('input choice:')
if hasattr(dog, choice):
func = getattr(dog, choice)
func()
else:
print('方法不存在')
- 动态添加属性、方法