In [1]:
#其实__str__相当于是str()方法 而__repr__相当于repr()方法。str是针对于让人更好理解的字符串格式化,而repr是让机器更好理解的字符串格式化。
class Test():
def __init__(self,word):
self.word=word
def __str__(self):
return "My name is %s" % self.word
def __repr__(self):
return "My name is %s" % self.word
a=Test('jack')
print(str(a))
print(repr(a))
My name is jack
My name is jack
In [2]:
#__hash__() hash()函数的装饰器
class Test(object):
def __init__(self, world):
self.world = world
x = Test('world')
p = Test('world')
print(hash(x) == hash(p))
print(hash(x.world) == hash(p.world))
#以上是hash函数的用法,用于获取对象的哈希值
class Test2(object):
def __init__(self, song):
self.song = song
def __hash__(self):
return 1241
x = Test2('popo')
p = Test2('janan')
print(x, hash(x))
print(p, hash(p))
False
True
<__main__.Test2 object at 0x05E4E790> 1241
<__main__.Test2 object at 0x05E4E7F0> 1241
In [4]:
#__getattr__() 一旦我们尝试访问一个并不存在的属性的时候就会调用,而如果这个属性存在则不会调用该方法。
class Test(object):
def __init__(self, world):
self.world = world
def __getattr__(self, item):
return '不存在的属性'
x = Test('jack')
print(x.world1)
不存在的属性
In [5]:
#__setattr__() 所有设置参数属性的方法都必须经过这个魔法方法
class Test(object):
def __init__(self, world):
self.world = world
def __setattr__(self, name, value):
#判断变量名
if name == 'world':
object.__setattr__(self, name, value+'!')
else:
object.__setattr__(self, name, value)
app=Test('jack')
print(app.world)
app.world='Tom'
print(app.world)
jack!
Tom!
In [6]:
#__delattr__()
class Test(object):
def __init__(self, world):
self.world = world
def __delattr__(self, item):
object.__delattr__(self, item)
app=Test('jack')
print(app.world)
del app.world
print(app.world)
jack
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-46b34955fb6c> in <module>
10 print(app.world)
11 del app.world
---> 12 print(app.world)
AttributeError: 'Test' object has no attribute 'world'
In [11]:
#__getattribute__() 拦截所有的属性获取
class Test(object):
def __init__(self, world):
self.world = world
def __getattribute__(self, item):
print('获取: %s' % item)
return '失败'
app=Test('jack')
print(app.world)
app1=Test('Tom')
print(app.world)
获取: world
失败
获取: world
失败
python常用魔法方法
猜你喜欢
转载自blog.csdn.net/wszsdsd/article/details/89135558
今日推荐
周排行