#######Application of magic method#######
##Constructor and destructor of magic method
#Constructor destructor
class People(object): def __init__(self,name,age): # Bind the property and object name together to make it easy to access the property of the object self.name =name self.age= age print('Object created successfully') # Destructor, when you delete an object, automatically calls the method. # del object name or after program execution def __del__(self): print('Delete object succeeded') if __name__ =="__main__": p1 =People('kebo', 24)
Operation result:
You can see that the del method is automatically executed after instantiation.
##str and repr methods (string display of objects)
class People(object): def __init__(self, name, age): # Bind the property and object name together to make it easy to access the property of the object self.name = name self.age = age print('Object created successfully') # Destructor, when you delete an object, automatically calls the method. # del object name or after program execution def __del__(self): print('Delete object succeeded') # __str and repr are both used to display the string of an object in different scenarios # If there is no str, the contents of the repr method are automatically called def __str__(self): return 'People(%s, %d)' % (self.name, self.age) def __repr__(self): # Print (repr (object name)) or direct in interactive environment: object name return "People(%s)" % (self.name) if __name__ == "__main__": p1 = People('kebo', 24) print(p1) print(p1.__str__())
class People(object): def __init__(self, name, age): # Bind the property and object name together to make it easy to access the property of the object self.name = name self.age = age print('Object created successfully') # Destructor, when you delete an object, automatically calls the method. # del object name or after program execution def __del__(self): print('Delete object succeeded') # __str and repr are both used to display the string of an object in different scenarios # If there is no str, the contents of the repr method are automatically called # def __str__(self): # return 'People(%s, %d)' % (self.name, self.age) def __repr__(self): # Print (repr (object name)) or direct in interactive environment: object name return "People(%s)" % (self.name) if __name__ == "__main__": p1 = People('kebo', 24) print(p1) print(p1.__str__())
##Format method of string and format magic method
-The format method of string;
1 fill string with position
print("name:{0}, age:{1}, scores:{2}".format('kobe', 24, [8, 24, 81])) print("name:{0}, age:{1}, scores:{0}".format('kobe', 10)) print("name:{0}, id:{1:.2f}".format('kobe', 3.1415926))
2 fill string with key value
d = {'max': 100, 'min': 10} print("MAX: {max}, MIN:{min}".format(max=100, min=10)) print("MAX: {max}, MIN:{min}".format(**d))
3 object oriented operation
class Book(object): def __init__(self, name, author, state, bookindex): self.name = name self.author = author self.state = state self.bookindex = bookindex def __repr__(self): return "Book(%s, %d)" % (self.name, self.state) b = Book('python', 'houzeyu', 1, '24&8') print(b) print("Name:{0.name}, State:{0.state}, Author:{0.author}".format(b)) print("Name:{b.name}, State:{b.state}, Author:{b.author}".format(b=b))
-format magic method
class Date(object): def __init__(self, year, month, day): self.year = year self.month = month self.day = day # Format method: automatically called when format (object name) def __format__(self, format_spec=None): if not format_spec: return "%s-%s-%s" %(self.year, self.month, self.day) else: if format_spec == 'ymd': return "%s-%s-%s" %(self.year, self.month, self.day) elif format_spec == 'dmy': return "%s/%s/%s" %(self.day, self.month, self.year) else: return "error format" d = Date(2019, 9, 5) print(format(d)) print(format(d, 'ymd')) print(format(d, 'dmy'))
##Class
- @property
1)
class Book(object): def __init__(self, name, author, state, bookIndex): self.name = name self.author = author self.__state = state self.bookIndex = bookIndex # Turn a class method into a class property # When used, there is no decorator b.state() # When using, there is a decorator b.state @property def state(self): if self.__state == 0: return 'Lent out' elif self.__state == 1: return 'Not loaned out' else: return "Abnormal state" # When the attribute state is modified, the following method is executed automatically; b.state = 10 @state.setter def state(self, value): # if value == 0 or value == 1: if value in (0, 1): # Update Book status self.__state = value @state.deleter def state(self): print("is deleteing......") def __str__(self): return 'Book(%s, %d)' % (self.name, self.__state) b = Book('python', 'guido', 1, '1122334') # print(b.state) # # # 1) . the state of books can be changed by people, not limited to 0 or 1; # 2) How to display the status of books in a friendly way? # b.state = 10 # print(b.state) # 3) . the problem is solved, but the call is complex and the readability is not high # print(b.get_state()) # print(b.set_state(10)) # print(b.get_state()) # 4). print(b.state) b.state = 0 print(b.state) del b.state
2)
class Book(object): def __init__(self, name, author, state, bookIndex): self.name = name self.author = author # 0: 'lent' 1: 'not lent' self.__state = state self.bookIndex = bookIndex def get_state(self): if self.__state == 0: return 'Lent out' elif self.__state == 1: return 'Not loaned out' else: return "Abnormal state" def set_state(self, value): # if value == 0 or value == 1: if value in (0,1): # Update Book status self.__state = value def del_state(self): print("is deleteing......") def __str__(self): return 'Book(%s, %d)' %(self.name, self.__state) state = property(fget=get_state, fset=set_state, fdel=del_state) b = Book('python', 'guido', 1, '1122334') # print(b.state) # # # 1) . the state of books can be changed by people, not limited to 0 or 1; # 2) How to display the status of books in a friendly way? # b.state = 10 # print(b.state) # 3) . the problem is solved, but the call is complex and the readability is not high # print(b.get_state()) # print(b.set_state(10)) # print(b.get_state()) # 4). print(b.state) b.state = 0 print(b.state) del b.state
##Slicing and indexing of classes
-Slicing and indexing
1) By index operation
class Student(object): def __init__(self, name, scores): self.name = name self.scores = scores # Support index; s[index] def __getitem__(self, index): return self.scores[index] # s [index] = modified value def __setitem__(self, index, value): self.scores[index] = value # del s [index] def __delitem__(self, index): del self.scores[index] s = Student('houzeyu', [8, 24, 81, 60]) print(s[0]) print(s[2]) s[3]= 35000 print(s[3]) print(s.scores) del s[1] print(s.scores) # All the attributes can be obtained as key values and corresponding value values, and encapsulated as a dictionary return print(s.__dict__)
Operation result:
2) Operation through dictionary
class Student(object): def __init__(self, name, scores): self.name = name self.scores = scores # Support index; s[key] def __getitem__(self, key): # print("get the value value corresponding to the index") return self.__dict__[key] # s[key] = modified value def __setitem__(self, key, value): self.__dict__[key] = value # del s[key] def __delitem__(self, key): del self.__dict__[key] s = Student('houzeyu', [8, 24, 81, 60]) print(s['name']) print(s['scores']) s['name'] = 'kobe' print(s['name']) s['scores'] = [1, 2, 3, 4] print(s['scores']) del s['name'] print(s)
3) slice
class Student(object): def __init__(self, name, scores): self.name = name self.scores = scores def __getitem__(self, key): return self.scores[key] def __setitem__(self, key, value): self.scores[key] = value def __delitem__(self, key): del self.scores[key] s = Student('houzeyu', [8, 24, 81, 60]) print(s[1:3]) s[1:3] = [0, 0] print(s[:]) del s[2:] print(s[:])
##Repetition and join and member operators
from collections import Iterable class Student(object): def __init__(self, name, scores): self.name = name self.scores = scores self.power = 100 # obj1 + obj2 def __add__(self, other): # Update the power attribute value of self object; self.power = self.power + other.power return self # obj1 * 3 def __mul__(self, other): return self.power * other # Member operator; item in obp1 def __contains__(self, item): return item in self.scores # Can be for loop iteration def __iter__(self): return iter(self.scores) def __repr__(self): return "Student:%s, %s" % (self.name, self.power) s1 = Student('kobe', [101, 100, 100]) s2 = Student('james', [100, 100, 100]) s3 = Student('curry', [100, 100, 100]) print(s1.power + s2.power + s3.power) print(s1*5) print(200 in s1)
##Class method and static method
class Date(object): def __init__(self, year, month, day): self.year = year self.month = month self.day = day # Echo common method, the object will be passed to echo by default def echo(self): return "%s %s %s" % (self.year, self.month, self.day) # The default is to pass the class itself to this method; @classmethod def as_string(cls, s): print(cls) month, day, year = s.split('/') d = cls(year, month, day) return d # The default python interpreter does not pass any parameters @staticmethod def is_valid(s): # Batch convert mm / DD / yyyy to shape (list generation, map) month, day, year = map(int, s.split('/')) return 0 < month <= 12 and 0 < day <= 31 and 1 < year < 9999 print(Date.as_string('12/10/2019').echo()) s = '10/10/2018' print(Date.is_valid(s))
##Object oriented reflection mechanism
- hasattr, getattr, setattr, delattr
class Student(object): def __init__(self, name, age): self.name = name self.__age = age def get_score(self): return "score" def get_grade(self): return 'grade' s1 = Student("kobe", 81) # hasattr: determine whether the object contains the corresponding attribute or method name; print(hasattr(s1, 'name')) print(hasattr(s1, '__age')) # Private property, private method, can not be judged; print(hasattr(s1, 'score')) print(hasattr(s1, 'get_score')) print(hasattr(s1, 'set_score')) # getattr: used to return the property value of the object or the method body corresponding to the method name; print(getattr(s1, 'name')) print(getattr(s1, '__age', 'no attr')) print(getattr(s1, 'get_score', 'no method')) # Get the method name. If you want to execute the method, just call it directly print(getattr(s1, 'set_score', 'no method')) # Get the method name. If you want to execute the method, just call it directly # setattr: # Modify the value of a property setattr(s1, 'name', 'james') print(getattr(s1, 'name')) # Add a property and its corresponding value; setattr(s1, 'score', 100) print(getattr(s1, 'score')) # Modification method def get_score1(): return "This is the content of the modified method" setattr(s1, 'get_score', get_score1) print(getattr(s1, 'get_score')()) def set_score(): return "This is the way to add" # Adding method setattr(s1, 'set_score', set_score) print(getattr(s1, 'set_score')()) # delattr delattr(s1, 'name') print(hasattr(s1, 'name')) print(hasattr(s1, 'set_score')) delattr(s1, 'set_score') print(hasattr(s1, 'set_score'))