类的内置方法/魔法方法
类的__new__(cls, *agrs, **kwargs)方法
new__方法会在创建类的实例对象的时候调用,本质就当我们创建一个类实例的时候会最先调用__new__方法创建一个实例,至于__init__方法也是在创建完实例之后才执行,所以__new()方法在__init__方法之前执行
类的__init__()方法
init__方法会在创建类的实例对象的时候调用(在__new()方法之后,也就是这个实例刚被造出来的时候执行)
可遍历数据对象的__len__()方法
触发时机:使用len(对象) 的时候触发
参数:一个参数self
返回值:必须是一个整型
作用:可以设置为检测对象成员个数,但是也可以进行其他任意操作
注意:返回值必须必须是整数,否则语法报错,另外该要求是格式要求。
print([1, 3, 5].__len__())
print("asasasasa".__len__())
类的__setattr__()方法
__setattr__方法,setattr__方法和__dict 方法可以说是一对,一个是展示实例的所有属性值,一个是设置对象的属性值 ,当在对象内部设置或者生成新的属性和值得时候会调用__setattr__方法将这个属性和值插入到__dict__的字典里面,__setattr__方法内部的实现基本可以认为是给__dict__的字典插入新的键值的动作,可以对其进行重写但是要注意不要影响实例对象的属性赋值功能
class Fun():
def __init__(self):
self.name = "Liu"
self.age = 12
self.male = True
def __setattr__(self, key, value):
print("*" * 50)
print("插入前打印current __dict__ : {}".format(self.__dict__))
# 属性注册
self.__dict__[key] = value
print("插入后打印current __dict__ : {}".format(self.__dict__))
def test(self):
self.new_key = "new_value"
fun = Fun()
print("===============")
fun.test()
# **************************************************
# 插入前打印current __dict__ : {}
# 插入后打印current __dict__ : {'name': 'Liu'}
# **************************************************
# 插入前打印current __dict__ : {'name': 'Liu'}
# 插入后打印current __dict__ : {'name': 'Liu', 'age': 12}
# **************************************************
# 插入前打印current __dict__ : {'name': 'Liu', 'age': 12}
# 插入后打印current __dict__ : {'name': 'Liu', 'age': 12, 'male': True}
# ===============
# **************************************************
# 插入前打印current __dict__ : {'name': 'Liu', 'age': 12, 'male': True}
# 插入后打印current __dict__ : {'name': 'Liu', 'age': 12, 'male': True, 'new_key': 'new_value'}
类的__getattr__方法
__getattr__是作用于属性查找的最后一步,当调用属性的时候会在最后调用__getattr__函数
用__getattr__方法可以处理调用属性异常
class Student(object):
def __getattr__(self, attrname):
if attrname == "age":
return 'age:40'
else:
raise AttributeError(attrname)
x = Student()
print(x.age) # 40
print(x.name)
类的__del__()方法
删除对象的时候会先调用__del__()方法,之后再删除对象,包括程序运行完之后,也会调用,如下
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __del__(self):
print("=================我被调用了===========")
p = Person("LiMing", 30)
print("=============程序最后一行===============")
打印结果
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __del__(self):
print("=================我被调用了===========")
p = Person("LiMing", 30)
del p
print("=============程序最后一行===============")
`类的__str__() 方法
当打印这个类的实例对象的时候,会打印这个类中的__str__方法返回的值,创建类时默认的__str__
方法返回的是内存地址,也可以自己定义类时重写__str__`方法
可以重写__str__方法,但是必须要有返回值,__str__方法的返回值就是你打印这个对象的时候打印出来的东西,默认是对象和他的内存地址,如果重写的话会根据你的重写的返回值来显示,如果打印类名的话返回的是类的显示 必须注意重写__str__方法需要返回字符串的类型不然会报错
触发时机:使用print(对象)或者str(对象)的时候触发
参数:一个self接收对象
返回值:必须是字符串类型
作用:print(对象时)进行操作,得到字符串,通常用于快捷操作
注意:无
class Student(object):
def __init__(self):
pass
def __str__(self):
return "我是新的显示内容"
class Student2(object):
def __init__(self):
pass
test1 = Student()
test2 = Student2()
print(test1)
print(test2)
print(Student)
print(Student2)
# 我是新的显示内容
# <__main__.Student2 object at 0x0000016BD779D630>
# <class '__main__.Student'>
# <class '__main__.Student2'>
类的__add__()
方法
方法:定义对象间的加法操作,可以使用+运算符进行操作。示例:
class Student(object):
def __init__(self, a):
self.a = a
pass
def __add__(self, other):
return self.a + other.a
obj1 = Student(10)
obj2 = Student(11)
print(obj1 + obj2)
# 21
obj3 = Student("pyt")
obj4 = Student("hon")
print(obj3 + obj4)
# python
类的__call__()
方法:
定义一个可调用的对象,使实例对象可以像函数一样被调用。示例:
class Student(object):
def __init__(self, a):
self.a = a
pass
def __call__(self, a, b):
return a + b
obj3 = Student(3)
print(obj3(5, 7))
# 12
python处理对象/类的 内置函数
内置函数 getattr()
getattr是Python中的内置函数,用于获取一个实例对象的属性值。这个函数是动态获取属性的一种方式,特别适用于你事先不知道要获取哪个属性,或者属性名是在运行时确定的情况。
object: 要从中获取属性的对象。
name: 属性的名字,必须是字符串。
default: 可选参数。如果指定的属性不存在,getattr会返回这个值。如果没有提供此参数并且属性不存在,则会引发AttributeError。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
# 获取实例对象p的name属性基本差不对等于print(p.name)
print(getattr(p, "name")) # 输出: Alice
# 获取实例对象p的age属性基本差不对等于print(p.age)
print(getattr(p, "age")) # 输出: 30
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
print(getattr(p, "name")) # 输出: Alice
print(getattr(p, "age")) # 输出: 30
# 第三个参数的作用是,如果设置第三个参数的话,那么如果没有这个属性的话就会返回第三个参数
print(getattr(p, "address", "Unknown")) # 输出: Unknown
print(getattr(p, "xxxxxxxxxx")) # 会引发AttributeError。
内置函数 setattr()
setattr用于设置或修改对象的属性值。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("LiMing", 30)
# 将实例对象p的name属性设置或者修改成字符串"Bob" 差不多等于p.name = "Bob"
setattr(p, "name", "Bob")
print(p.name) # 输出: Bob
内置函数 hasattr()
hasattr用于检查实例对象是否具有给定的属性。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("LiMing", 30)
if hasattr(p, "name"):
print("Person has a name attribute!")
内置函数 delattr()
hasattr用于检查实例对象是否具有给定的属性。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("LiMing", 30)
print(p.name, p.age)
# 删除实例对象的age属性
delattr(p, "age")
print(p.name, p.age)
# LiMing 30
# Traceback (most recent call last):
# File "C:/Users/魏航/Desktop/weihang_python_test_dir/wh.py", line 26, in <module>
# print(p.name, p.age)
# AttributeError: 'Person' object has no attribute 'age'
类的__dict__属性(方法) 函数/类引用地址或者实例对象调用
__dict__方法两种用法
-
类名.__dict__ 的结果是一个包含当前类的所有方法名字和对象的字典
-
类的实例对象.__dict__ 的结果是一个包含当前实例对象当前的所有属性名和属性值的一个字典
class AnotherFun:
def __init__(self):
self.name = "Liu"
print(self.__dict__)
self.age = 12
print(self.__dict__)
self.male = True
print(self.__dict__)
another_fun = AnotherFun()
# {'name': 'Liu'}
# {'name': 'Liu', 'age': 12}
# {'name': 'Liu', 'age': 12, 'male': True}
类的__doc__属性(方法) 函数/类引用地址或者实例对象调用
该方法通常会输出指定对象中的注释部分
class Debug:
"""
Debug类的函数说明(注释)
"""
def __init__(self):
"""
__init__方法的函数说明(注释)
"""
self.x = 5
main = Debug()
print(main.__doc__) # Debug类的函数说明(注释)
print(main.__init__.__doc__) # __init__方法的函数说明(注释)
print(Debug.__doc__) # Debug类的函数说明(注释)
print(Debug.__init__.__doc__) # __init__方法的函数说明(注释)
__qualname__属性(方法)和__name__属性(方法) 函数/类引用地址调用
__name__函数或类的名字。
__qualname__表示的是函数或类的限定名,通俗点讲就是带了定语的名字,定语就是从模块顶层到定义处的路径。
def f1():
pass
class C():
def f2(self):
pass
class C2():
def f3(self):
pass
print(f1.__name__) # f1
print(C.f2.__name__) # f2
print(C.C2.f3.__name__) # f3
print("=====================")
print(f1.__qualname__) # f1
print(C.f2.__qualname__) # C.f2
print(C.C2.f3.__qualname__) # C.C2.f3