内置方法
目录
内置方法
-
__init__(完成对象的初始化)
class Foo: def __init__(self,name,pwd): self.name = name self.pwd = pwd p = Foo('name','pwd')
-
_str__:如果不重写_str__ print打印会打印出内存地址
class Foo: def __init__(self,name,pwd): self.name = name self.pwd = pwd p = Foo('name','pwd') print(p.__str__())#<__main__.Foo object at 0x00000239F5C69BC8>
class Foo: def __init__(self,name,pwd): self.name = name self.pwd = pwd def __str__(self): return self.name p = Foo('name','pwd') print(p.__str__())#name # #相当于上面那句 print(p)#name
小知识
l=[1,2,3] #本质也是调用list的__str__方法 print(l)
-
_repr__:跟str类似,在交互式命令下直接写变量名,会执行_repr__
-
__getattr__:#如果去对象中取属性,一旦取不到,会进入到__getattr__
-
_selattr__:如果去对象中赋值属性,一旦取不到,会进入到_selattr__
-
__delattr__:#如果删除对象中的属性,会进__delattr__
class Foo: def __init__(self,name): self.name = name def __getattr__(self, item): return 'getattr' def __set__(self, instance, value): return 'setattr' def __delattr__(self, item): return "delattr" f = Foo('nick') print(f.name)#nick print(f.age)#getattr,如果去对象中取属性,一旦取不到,会进入到__getattr__ print(f.__dict__)#{'name': 'nick'} print(f.name)#nick f.sex = 'male' print(f.__dict__)#{'name': 'nick', 'sex': 'male'} del f.name #删除不掉,因为有delattr print(f.__dict__)#{'name': 'nick', 'sex': 'male'}
原来字典使用方式
di=dict(name='lqz',age=18) print(di) print(di['name']) print(di.name) di.sex='male' #
写一个类继承字典,让它可以 . 取值,可以中括号取值
class Mydict(dict): 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='lqz',age=18) print(di['name']) print(di.name) di.sex='male' di['sex']='male' print(di['name']) print(di.name) di.sex=19 print(di.sex) di['sex']='male' print(di.sex)
__item__系列 对象通过[] 中括号取值,赋值,删除值的时候,会调用
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('nick') print(f['name']) __call__ 对象加括号会调用它 class Foo: def __call__(self): print('xxxx') f=Foo() f()
class Mydict():
def __getattr__(self, item):
print('xxx')
return '该属性不存在'
m=Mydict()
print(m.name)