七、__setitem__, __getitem__, __delitem__ |
item series
class Foo: def __init__(self, name): self.name = name def __getitem__(self, item): # print('getitem...') #print(item) return self. __dict__ .get(item) #The dictionary get method will take the value if there is one, and no error will be reported if there is no def __setitem__(self, key, value): # print('setitem...') # print(key,value) self.__dict__[key] = value def __delitem__(self, key): # print('delitem...') # print(key) # self.__dict__.pop(key) del self.__dict__[key] obj = Foo ( ' egon ' ) # 1. View attributes # obj. attribute name # The item series is to simulate the object as a dictionary, and you can access obj[ ' name ' ] like a dictionary # complete the effect of obj.name value in this form """ getitem... name """ print(obj['name']) # 2. Set properties # obj.sex = 'male' obj[ ' sex ' ] = ' male ' print(obj.__dict__) print(obj.sex) # 3. Delete attribute # del obj.name del obj[ ' name ' ] print (obj. __dict__ ) """ {'sex': 'male'} """
八 、 __ str__, __repr__, __format__ |
Change the object's string display __str__, __repr__
to customize the format string __format__
d = dict({ ' name ' : ' egon ' }) print (isinstance(d, dict)) # True, d is an instance of class dict print (d) class Foo: pass obj = Foo() print (obj) """ is also a print object, the display form is completely different, and printing always hopes to have a prompt function like the previous one. {'name': 'egon'} <__main__.Foo object at 0x10401ad68> """ # After the __str__ method is defined, the __str__ method under the object will be triggered when the object is printed, and the result of the string will be used as the result of printing. class People: def __init__ (self, name, age): self.name = name self.age = age def __str__ (self): #Must return a string # print("Trigger __str__ method:") return ' <name:%s,age:%s> ' % (self.name, self.age) obj = People('egon', 18) print(obj) """ <name:egon,age:18> """
format_dict= { ' nat ' : ' {obj.name}-{obj.addr}-{obj.type} ' , #school name-school address-school type ' tna ' : ' {obj.type}:{obj. name}:{obj.addr} ' , #School type:School name:School address ' tan ' : ' {obj.type}/{obj.addr}/{obj.name} ' , #School type/School address/ school name } class School: def __init__ (self,name,addr,type): self.name=name self.addr=addr self.type=type def __repr__(self): return 'School(%s,%s)' %(self.name,self.addr) def __str__(self): return '(%s,%s)' %(self.name,self.addr) def __format__(self, format_spec): # if format_spec if not format_spec or format_spec not in format_dict: format_spec='nat' fmt=format_dict[format_spec] return fmt.format(obj=self) s1=School('oldboy1','北京','私立') print('from repr: ',repr(s1)) print('from str: ',str(s1)) print(s1) ''' str function or print function--->obj.__str__() repr or interactive interpreter--->obj.__repr__() If __str__ is not defined, then __repr__ will be used instead of output Note: The return value of these two methods must be a string, otherwise an exception will be thrown ''' print(format(s1,'nat')) print(format(s1,'tna')) print(format(s1,'tan')) print(format(s1,'asfdasdffd'))
date_dic={ 'ymd':'{0.year}:{0.month}:{0.day}', 'dmy':'{0.day}/{0.month}/{0.year}', 'mdy':'{0.month}-{0.day}-{0.year}', } class Date: def __init__(self,year,month,day): self.year=year self.month=month self.day=day def __format__(self, format_spec): if not format_spec or format_spec not in date_dic: format_spec='ymd' fmt=date_dic[format_spec] return fmt.format(self) d1=Date(2016,12,29) print(format(d1)) print('{:mdy}'.format(d1))
class A: pass class B(A): pass print (issubclass(B,A)) # B is a subclass of A, returns True a1 = A() print (isinstance(a1,A)) # a1 is an instance of A
Nine, slots |