__init__ 在對象實例化的時候自動調用的python
__repr__ 跟str相似,在交互式命令下直接寫變量名,會執行__repr__code
__str__對象
1.不寫__str__ class Foo: def __init__(self,name): self.name=name # def __str__(self): # return '['+self.name+']' f=Foo('nick') print(f.__str__())
<main.Foo object at 0x00000201444E77F0>繼承
2.寫__str__ class Foo: def __init__(self,name): self.name=name def __str__(self): return '['+self.name+']' f=Foo('xichen') print(f.__str__())
[xichen]內存
l=[1,2,3] # #本質也是調用list的__str__方法 print(l)
[1, 2, 3]資源
class Foo: def __init__(self,name): self.name=name def __setattr__(self, key, value): print('對象沒有這個屬性')
1.原來字典使用方式dict dic = dict(name='xichen',age=18) print(dic) print(dic ['name'])
{'name': 'xichen', 'age': 18}
xichenget
2.寫一個類繼承字典,讓它能夠 .取值,能夠中括號取值 class Mydict(dict): # 繼承dic這個類 def __init__(self,**kwargs): super().__init__(**kwargs) def __getattr__(self, item): print(item) return self[item] def __setattr__(self, key, value): self[key]=value di=Mydict(name='xichen',age=18) print(di['name']) print(di.name) di.sex='male' di['sex']='male' di.age=18 print(di.age)
xichen
xichenit
18class
class Foo: def __init__(self,name): self.name=name def __getattr__(self, item): return '沒有這個字段' f = Foo('xichen') print(f.age)
沒有這個字段變量
class Foo: def __init__(self,name): self.name=name def __delattr__(self,item): self.__dict__.pop(item) print('刪除成功') del f.name print(f.__dict__)
刪除成功
{'age': 18}
class Foo: def __init__(self, name): self.name = name def __getitem__(self, item): name=getattr(self,item) # print(name) # print(self.__dict__[item]) return name # return self.__dict__[item] def __setitem__(self, key, value): print('obj[key]=lqz賦值時,執行我') self.__dict__[key] = value def __delitem__(self, key): print('del obj[key]時,執行我') self.__dict__.pop(key)
f=Foo('xichen') print(f['name'])
xichen
f['age'] = 18 print(f['age']) print(f.__dict__)
obj[key]=lqz賦值時,執行我
18
{'name': 'xichen', 'age': 18}
del f['age'] print(f.__dict__)
del obj[key]時,執行我
{'name': 'xichen'}
class Foo: def __call__(self): print('調用我 !') f=Foo() f()
調用我 !
with open('path','r') as f: pass