title: python常用魔法函数 date: 2022-01-06 11:28:20 categories:
- IT技术
- 编程语言
- python tags:
- IT技术
- 编程语言
- python
python常用魔法函数
摘要: 魔法函数是一类特殊的静态方法,可以在不修改类或对象本身的情况下实现常见的功能。下面将详细介绍常见的魔法函数及其作用。
1. __init__()
所有类的超类 object 都有一个默认包含 pass 的 __init__() 实现,这个函数会在对象初始化的时候调用。我们可以选择实现或不实现。建议实现,这样对象属性就不会被初始化,虽然仍然可以进行赋值,但隐式初始化更方便。例如:
class Foo(object):
def __init__(self, x):
self.x = x # 隐式初始化
# 隐式赋值
fo = Foo(5)
# 输出结果为5
2. __str__()
这个方法被 print() 函数调用。它返回一个字符串,如果没有特别返回,会被 str() 转换。例如:
print(dict()) # 输出: {}
3. __new__()
在 object 类中有一个静态方法 __new__(cls, *args, **kwargs),必须返回实例。实例返回后,__init__() 才会被调用。例如:
class Foo(object):
def __new__(cls):
print(type(cls))
return 123
4. __unicode__()
在 Django 中,__unicode__() 被用来处理 Unicode 字符的显示问题。例如:
class Foo(object):
def __unicode__(self):
return u'\u00e9' # 转化为小写
5. __call__()
允许对象像函数一样被调用。例如:
class Foo(object):
def __call__(self):
return "Hello"
fo = Foo()
print(fo()) # 输出: Hello
6. __len__()
调用时返回一个整数。例如:
class Foo(object):
def __len__(self):
return 2
print(len(Foo())) # 输出: 2
7. __repr__() 和 __str__()
str() 依赖 __str__(),repr() 依赖 __repr__()。例如:
class Foo(object):
def __repr__(self):
return "Hello"
print(repr(Foo())) # 输出: u'Hello'
print(str(Foo())) # 输出: Hello
8. __setattr__() 和 __getattr__()
允许控制属性的设置和获取。例如:
class Foo(object):
def __setattr__(self, name, value):
print("setattr called", name, value)
super(Foo, self).__setattr__(name, value)
def __getattr__(self, name):
print("getattr called", name)
return super(Foo, self).__getattr__(name)
9. __getattribute__()
与 __getattr__() 相似,用于属性是否存在时的调用。例如:
class Foo(object):
def __getattribute__(self, name):
print("getattribute called", name)
return super(Foo, self).__getattribute__(name)
10. __delattr__()
删除属性时调用,需谨慎使用。例如:
class Foo(object):
def __delattr__(self, name):
print("Deleting attribute", name)
super(Foo, self).__delattr__(name)
11. __setitem__() 和 __getitem__()
支持赋值和获取,如字典。例如:
class Foo(object):
def __getitem__(self, key):
print("Getting item", key)
return super(Foo, self).__getitem__(key)
def __setitem__(self, key, value):
print("Setting item", key, "to", value)
super(Foo, self).__setitem__(key, value)
12. __delitem__()
删除项的方法。例如:
class Foo(object):
def __delitem__(self, key):
print("Deleting item", key)
super(Foo, self).__delitem__(key)
来源:https://www.cnblogs.com/small-office/p/9337297.html