Python advanced (7): Object-oriented advanced, python advanced object-oriented
Learned the inheritance, polymorphism, and encapsulation of the three object-oriented features. Today, let's take a look at some advanced object-oriented content, reflection and some built-in functions of classes.
I. isinstance and issubclass
Class Foo: passclass Son (Foo): passs = Son () # determine whether an object is an object of this class. pass two parameters (object, class) print (isinstance (s, son) print (isinstance (s, Foo) # type is more accurate print (type (s) is Son) print (type (s) is Foo) # determine whether a class is a subclass of another type. pass two parameters (subclass, parent class) print (issubclass (Son, Foo) print (issubclass (Son, object )) print (issubclass (Foo, object) print (issubclass (int, object ))
Ii. Reflection
The concept of reflection was first proposed by Smith in 1982. It mainly refers to the ability of a program to access, detect, and modify its own state or behavior (introspection ). The proposal of this concept soon led to research on application reflectivity in the computer science field. It was first adopted by the design field of programming language, and has made achievements in Lisp and object-oriented aspects.
Reflection in python object-oriented: operations on Object-related attributes in the form of strings. Everything in python is an object (reflection can be used)
Four functions that can be reflected: hasattr, getattr, setattr, delattr
The following method applies to classes and objects (everything is an object, and the class itself is also an object)
Class Foo: def _ init _ (self): self. name = 'egon' self. age = 73 def func (self): print (123) egg = Foo () # common: # hasattr # getattr # print (hasattr (egg, 'name ')) print (getattr (egg, 'name') if hasattr (egg, 'func'): # Return bool Foo_func = getattr (egg, 'func ') # If this method or attribute exists, the memory address of the attribute value or method is returned. # If it does not exist, an error is returned. Therefore, use Foo_func () with hasattr. # not commonly used: # setattr (egg, 'sex', 'Property value') # print (egg. sex) # def show_name (self): # print (self. name + 'SB ') # setattr (egg, 'sh _ name', show_name) # egg. sh_name (egg) # show_name (egg) # egg. sh_name () # delattr (egg, 'name') # print (egg. name) # print (egg. name) # egg. func () # print (egg. _ dict _) # reflection # You can use strings to access object attributes and call object methods.
Reflection Example 1
Class Foo: f = 123 # class variable @ classmethod def class_method_demo (cls): print ('class _ method_demo ') @ staticmethod def static_method_demo (): print ('static _ method_demo ') # if hasattr (Foo, 'F'): # print (getattr (Foo, 'F') print (hasattr (Foo, 'class _ method_demo ')) method = getattr (Foo, 'class _ method_demo ') method () print (hasattr (Foo, 'static _ method_demo') method2 = getattr (Foo, 'static _ method_demo ') method2 () # The class is also an object
Reflection Example 2
Import my_module # print (hasattr (my_module, 'test') # func_test = getattr (my_module, 'test') # func_test () # getattr (my_module, 'test ') () # import other module application reflection from my_module import testdef demo1 (): print ('demo1') import sysprint (_ name __) # '_ main _' print (sys. modules) # '_ main _': <module '_ main _' from 'd:/Python code file storage directory/S6/day26/6 reflection 3. py'> module_obj = sys. modules [_ name _] # sys. modules ['_ main _'] # module_obj: <module '_ main _' from 'd: /Python code file storage directory/S6/day26/6 reflection 3. py '> print (module_obj) print (hasattr (module_obj, 'demo1') getattr (module_obj, 'demo1') () # apply reflection in this module
Reflection Example 3
# Object # class # module: This module and the imported module def register (): print ('register ') def login (): passdef show_shoppinglst (): pass # print ('register, logon') ret = input ('Welcome, please enter your operation: ') import sysprint (sys. modules) # my_module = sys. modules [_ name _] # if hasattr (my_module, ret): # getattr (my_module, ret) () if ret = 'registration': register () elif ret = 'login': login () elif ret = 'shopping': show_shoppinglst ()
Reflection Example 4
def test(): print('test')
My_module (the module used in the third example)
Iii. built-in functions of the class
1. _ str _ and _ repr __
Class Foo: def _ init _ (self, name): self. name = name def _ str _ (self): return '% s obj info in str' % self. name def _ repr _ (self): return 'obj info in repr 'f = Foo ('egon') # print (f) print ('% s' % f) print ('% R' % f) print (repr (f) # f. _ repr _ () print (str (f) # When printing an object, if str is implemented, the returned value in the print # When str is not implemented, the repr method will be called # But when you format the string, % s and % r will call _ str _ and _ repr __# both during string formatting when printing objects, repr methods can be used as substitutes for str methods # but not vice versa # for friendly Representation Object. If the str and repr methods are used, you can only implement one: First implement repr
2. _ del __
Class Foo: def _ del _ (self): print ('execute me ') f = Foo () print (123) print (123) print (123) # destructor: This method is automatically triggered when an object is released in the memory. # Note: This method does not need to be defined. Because Python is a high-level language, programmers do not need to worry about memory allocation and release when using it, because this job is executed by the Python interpreter, therefore, the interpreter automatically triggers the execution of destructor calls during garbage collection.
3. item Series
_ Getitem __\__ setitem __\__ delitem __
class Foo: def __init__(self): self.name = 'egon' self.age = 73 def __getitem__(self, item): return self.__dict__[item] def __setitem__(self, key, value): # print(key,value) self.__dict__[key] = value def __delitem__(self, key): del self.__dict__[key]f = Foo()print(f['name'])print(f['age'])f['name'] = 'alex'# del f['name']print(f.name)f1 = Foo()print(f == f1)
4. _ new __
# Class A: # def _ init _ (self): # There is A way to help you create self # print ('in init function') # self. x = 1 # def _ new _ (cls, * args, ** kwargs): # print ('In new function') # return object. _ new _ (A, * args, ** kwargs) # a = A () # B = A () # c = A () # d = () # print (a, B, c, d) # Singleton: def _ new _ (cls, * args, ** kw) in Singleton mode ): if not hasattr (cls, '_ instance'): cls. _ instance = object. _ new _ (cls, * args, ** kw) return cls. _ instanceone = Singleton () two = Singleton () three = Singleton () go = Singleton () print (one, two) one. name = 'Alex 'print (two. name)
5. _ call __
Class Foo: def _ init _ (self): pass def _ call _ (self, * args, ** kwargs ): print ('_ call _') obj = Foo () # Run _ init _ obj () # Run _ call _ Foo ()() # execute _ init _ and execute _ call __# the execution of the constructor is triggered by the creation object, that is, the object = Class Name (); the execution of the _ call _ method is triggered by brackets after the object, that is, the object () or class ()()
6. _ len __,_ Hash __
class Foo: def __len__(self): return len(self.__dict__) def __hash__(self): print('my hash func') return hash(self.name)f = Foo()print(len(f))f.name = 'egon'print(len(f))print(hash(f))
7. _ eq __
Class A: def _ init _ (self): self. a = 1 self. B = 2 def _ eq _ (self, obj): if self. a = obj. a and self. B = obj. b: return Truea = A () B = A () print (a = B) #__ eq _ controls the result of =
8. built-in function instances
Class FranchDeck: ranks = [str (n) for n in range (2, 11)] + list ('jqka ') suits = ['redhearts', 'Ban', 'plum blossom ', 'Tao'] def _ init _ (self): self. _ cards = [Card (rank, suit) for rank in FranchDeck. ranks for suit in FranchDeck. suits] def _ len _ (self): return len (self. _ cards) def _ getitem _ (self, item): return self. _ cards [item] deck = FranchDeck () print (deck [0]) from random import choiceprint (choice (deck) print (choice (deck ))
Card games
Class FranchDeck: ranks = [str (n) for n in range (2, 11)] + list ('jqka ') suits = ['redhearts', 'Ban', 'plum blossom ', 'Tao'] def _ init _ (self): self. _ cards = [Card (rank, suit) for rank in FranchDeck. ranks for suit in FranchDeck. suits] def _ len _ (self): return len (self. _ cards) def _ getitem _ (self, item): return self. _ cards [item] def _ setitem _ (self, key, value): self. _ cards [key] = valuedeck = FranchDeck () print (deck [0]) from random import choiceprint (choice (deck) print (choice (deck )) from random import shuffleshuffle (deck) print (deck [: 5])
Card Game 2
Class Person: def _ init _ (self, name, age, sex): self. name = name self. age = age self. sex = sex def _ hash _ (self): return hash (self. name + self. sex) def _ eq _ (self, other): if self. name = other. name and other. sex = other. sex: return Truep_lst = [] for I in range (84): p_lst.append (Person ('egon', I, 'male') print (p_lst) print (set (p_lst) # As long as the name and age are the same, one person is de-duplicated by default.
Deduplication