self 和 cls 的区别
一句话,cls 代表类,self 代表实例对象
getattr()
getattr() 是一个内置函数,用于从对象中获取属性值。如果指定的属性存在,则返回该属性的值;如果属性不存在,则会引发 AttributeError(除非提供了默认值)。
getattr() 的基本语法如下:
getattr(object, name[, default])
- object:你想要获取其属性的对象。
- name:你想要获取的属性的名称(作为字符串)。
- default(可选):如果属性不存在,则返回的值。如果未提供此参数,并且属性不存在,则会引发 AttributeError。
python
class MyClass:
def __init__(self):
self.my_attribute = "Hello, World!"
obj = MyClass()
# 使用 getattr 获取属性
value = getattr(obj, "my_attribute")
print(value) # 输出: Hello, World!
# 尝试获取不存在的属性,但没有提供默认值
try:
value = getattr(obj, "non_existent_attribute")
except AttributeError:
print("该属性不存在")
# 尝试获取不存在的属性,但提供了默认值
value = getattr(obj, "non_existent_attribute", "默认值")
print(value) # 输出: 默认值python
# 定义一个模块(通常在一个单独的文件中,但这里为了示例我们在同一个脚本中)
class MyCuCls:
pass
# 假设我们有一个模块对象 module,它有一个名为 MyCuCls 的属性
# 在实际情况中,您可能会使用 import 语句导入一个模块
# 但为了示例,我们直接创建一个字典来模拟模块
module = {
'MyCuCls': MyCuCls
}
# 使用 getattr 从模拟的模块中获取 MyCuCls 类
value = getattr(module, "MyCuCls")
print(value) # 这将打印 <class '__main__.MyCuCls'>,表示我们成功获取了类__del__()
创建对象后,Python解释器默认调用__init__()方法。当删除一个对象时,Python解释器也会默认调用一个方法,这个方法为__del__()方法。在Python中,对于开发者来说很少会直接销毁对象(如果需要,应该使用del关键字销毁)。Python的内存管理机制能够很好的胜任这份工作。也就是说,不管是手动调用del还是由Python自动回收都会触发__del__方法执行。
使用场景:
1、当删除对象时,Python解析器会默认调用__del__()方法
2、销毁(释放)内存中的对象时回调__del__()方法
enter(self)
with语句开始时调用。
exit(self, exc_type, exc_val, exc_tb)
with语句结束时调用。
python3
class MyContextManager:
def __enter__(self):
print("Entering the context")
# 这里可以返回一些对象,该对象将在with语句的as部分被绑定
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting the context")
# 这里可以进行一些清理工作,比如关闭文件、释放资源等
# 如果需要抑制异常,可以返回True
# 使用with语句和上下文管理器
with MyContextManager() as cm:
print("Inside the context")
# 输出:
# Entering the context
# Inside the context
# Exiting the context
# 当你执行 with MyContextManager() as cm: 这行代码时,MyContextManager 类的 __enter__ 方法会被调用。由于 __enter__ 方法返回了 self,你可以在 with 语句的 as 部分使用 cm 变量来引用这个上下文管理器对象。当 with 代码块结束时(在这个例子中是打印 "Inside the context" 之后),__exit__ 方法会被调用。
# 这种机制在需要设置和清理资源的场合特别有用,比如管理文件、网络连接、锁等。通过使用上下文管理器和 with 语句,你可以确保资源在使用后总是被正确地清理,即使在处理资源时发生了异常也是如此。call(self, [args...])
使对象可调用(如函数)。
__call__方法在Python中有很多用途,例如:
- 创建可调用对象,这些对象的行为类似于函数,但可以保存状态或具有其他属性。
- 实现装饰器,装饰器函数本身返回一个可调用对象。
- 创建工厂函数,这些函数返回可调用对象,这些对象根据提供的参数生成新的对象或执行其他操作。
- 在元编程中,动态地创建和调用函数或方法。
python3
class CallableClass:
def __call__(self, *args, **kwargs):
print("Called with arguments:", args, kwargs)
# 创建一个CallableClass的实例
instance = CallableClass()
# 使用圆括号调用该实例,就像调用函数一样
instance(1, 2, 3, key='value')
# 输出:
# Called with arguments: (1, 2, 3) {'key': 'value'}
---
class Timer:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print("def __call__")
start_time = time.time()
result = self.func(*args, **kwargs)
end_time = time.time()
print('执行时间:{}秒'.format(end_time - start_time))
return result
@Timer
def slow_func(n):
print("def slow_func")
time.sleep(n)
return n
print(slow_func(2)) # 同时打印出执行时间
# def __call__
# def slow_func
# 执行时间:2.00838041305542秒
# 2