Python full Stack development "17th article" Object-oriented reflection and built-in methods

Source: Internet
Author: User
Tags reflection

First, static methods (Staticmethod) and class methods (Classmethod)

Class method: There is a default parameter CLS, and can be called directly with the class name, you can interact with class properties (that is, you can use class properties)

static method: Let the method in the class be called directly by the class, just like the normal calling function

The same point of a class method and a static method: All can be called directly by the class, without the need to instantiate

The difference between a class method and a static method:

The class method must have a CLS parameter representing the class, and you can use the Class property

Static methods do not require parameters

Binding methods: Divided into common methods and class methods

Common method: A Self object is passed in by default and can only be called by an object-------bound to an object

Class method: A CLS object is passed in by default and can be called by classes and objects (not recommended)-----bound to a class

Unbound methods: Static methods: No default parameters are set and can be called by classes and objects (not recommended)-----unbound

# Staticmethod and Classmethodclass Student:    f = open (' Student ', encoding= ' Utf-8 ')    def __init__ (self):        Pass    @classmethod #类方法: There is a default parameter CLS, and you can directly use the class name to                 #调用, and you can also interact with class properties (that is, you can use class properties)    def show_student_info_class (CLS):        # f = open (' Student ', encoding= ' utf-8 ') for line in        cls.f:            name,sex = Line.strip (). Split (', ')            print ( Name,sex)    @staticmethod  #静态方法: can be called directly using the class name, just like a normal function call    def show_student_info_static (): #不用传self        f = open (' Student ', encoding= ' utf-8 ') for line in        f:            name,sex = Line.strip (). Split (', ')            print ( Name,sex) # egon = Student () # egon.show_student_info_static ()  #也可以这样调, but it is recommended to use the class name to tune # Egon.show_student_info_class () Student.show_student_info_class () #类名. Method Name () print ('-------------------') student.show_student_info_static () # Class name. Method Name ()

Isinstance and Issubclass

Isinstance (OBJ,CLS): Checks if obj is a CLS-compliant object (two arguments, one object, one class)

Issubclass (sub,super): Check sub is not super subclass (pass two parameters, one is subclass, one is parent class)

Class Foo:    passclass Son (Foo):    passs = Son () print (Isinstance (S,son))  #判断s是不是Son的对象print (type (s) is Son) Print (Isinstance (s,foo))  #判断s是不是Foo的对象  not accurate print (type (s) is Foo)  #type比较精准print (Issubclass (Son,foo)) # Determine son is not a subclass of Foo print (Issubclass (son,object)) print (Issubclass (foo,object)) print (Issubclass (int,object))

  

Second, reflection

Reflection: You can use a string to access the properties of an object, invoke the object's method (but not access the method), all objects in Python, can be used reflection.

There are four methods of reflection:

Hasattr:hasattr (Object,name) determines whether an object has a name attribute or a name method. Returns True if none returns False

GetAttr: Gets the property or method of the object and prints it if it exists. Hasattr and getattr matching use

It is important to note that if you return an object's method, the memory address of the object is returned, and if you need to run this method, you can add a pair later ()

SetAttr: Assigns a value to an object's property, and if the attribute does not exist, it is first created and then assigned

Delattr: Deletes a property specified by the object

# Setattrclass Foo:    def __init__ (self):        self.name = ' Egon '        self.age =-    def func (self):        print (' Hello ') egg = Foo () setattr (egg, ' sex ', ' man ') print (egg.sex) # 2.def Show_name (self):    print (self.name+ ' SB ') SetAttr ( Egg, ' sh_name ', show_name) egg.sh_name (egg) show_name (egg)
Delattr (egg, ' name ') print (egg.name)

1. Object Application Reflection

# Object Applied Reflection Class Foo:    def __init__ (self):        self.name = ' Egon '        self.age = "    def func (self):        print (' Hello ') egg = Foo () print (hasattr (egg, ' name '))  #先判断name在egg里面存在不存在print (getattr (egg, ' name ')) #如果为True它才去得到print (Hasattr (Egg, ' func ')) print (GetAttr (egg, ' func '))  #得到的是地址 # getattr (Egg, ' func ') ()  #在这里加括号才能得到 because Func is the method if Hasattr (Egg, ' func '):    getattr (Egg, ' func ') () Else:    print (' not found ')

2. Class Application Reflection

# class Application Reflection Class Foo:    f = 123    @classmethod    def class_method_dome (CLS):        print (' Class_method_dome ')    @staticmethod    def static_method_dome (): Print (        ' static_method_dome ') print (hasattr (Foo, ' Class_ Method_dome ') method = GetAttr (foo, ' Class_method_dome ') method () print ('------------') print (Hasattr (foo, ' Static_ Method_dome ') method1 = GetAttr (Foo, ' Static_method_dome ') method1 ()

3. Module Application Reflection

The application of the module is also divided into the reflection of other modules and reflected in this module.

# 1. Import other modules Reference import Mymoduleprint (hasattr (mymodule, ' Test ')) GetAttr (mymodule, ' Test ') () # # Here's GetAttr (mymodule, ' test ') ) () This sentence is equivalent to # p = getattr (mymodule, ' Test ') # p ()
# 2. Apply Reflection Def demo1 () in this module:    print (' wwww ') Import sys# print (sys.modules) module_obj = sys.modules[__name__]  #相当于 ' __main__ ' Print (module_obj) print (Hasattr (module_obj, ' demo1 ')) getattr (module_obj, ' demo1 ') ()
# example DEF registration ():    print (' regiester ') def login ():    print (' login ') def shopping ():    passprint (' Registration, login, shopping ') ret = input (' Please enter the action you want to do: ') import sysmy_module = sys.modules[__name__]  #利用sys模块导入一个自己的模块if hasattr (my_module,ret):    GetAttr (My_module,ret) ()

Three, built-in methods

1.__str__ and __repr__

Changing the string display of an object

#  __str__ and __repr__class Foo:    def __init__ (self,name):        self.name = name    def __repr__ (self):        Return ' obj in str '  #这里只能是return    # def __str__ (self):    #     return '%s ', obj in str '%SELF.NAMEF = Foo (' Egon ') pr Int (f)  #优先执行__str__里面的内容 # So you're not __repr__ to use it? # print ('%s '%f)  #执行的是__str__里面的返回值 # print ('%r '%f)  #执行的是__repr__里面的返回值print (' ============== ') print (str ( f)  #当执行str (f), the method of __str__ will be found, if not found, __repr__ this method to the replacement of print (Repr (f)) #1. When you print an object, if you implement the __str__ method, print __ return value in Str__ # 2. When __str__ is not implemented, the __repr__ method # 3 is called. But when you format the string,%s and%r call __str__ and __repr__ method # 4, respectively. The # __repr__ method can be used as a substitute for the __str__ method either when the string is formatted or when the object is printed, but not the other way # 5. Used to represent objects in a friendly manner. If the __str__ and __repr__ methods you can only implement one: first implement __REPR__

2.__del__

destructor, which automatically triggers execution when the object is freed in memory.

Note: This method is generally not defined because Python is a high-level language, and programmers do not need to be concerned with allocating and releasing memory because this work is done by the Python interpreter, so the destructor calls are automatically triggered by the interpreter when it is garbage collected.

Class Foo:    def __del__ (self):        print (' Execute me ') f= Foo () print (123) print (123) print (123) print (123)

3.item Series

There are __getitem__, __setitem__, __delitem__, respectively.

Class Foo:    def __init__ (self):        self.name = ' Egon '        self.age =        self.l=[1,2,3]    def __getitem__ ( Self, item):  #得到        # return  Self.l[item]        # return Self.__dict__[item]        # print (foo.__dict__)        Return 123    def __setitem__ (self, Key, value):  #修改        Print (key,value)        Self.__dict__[key] = value    def __delitem__ (self, key):  #删除        del self.__dict__[key]f = Foo () print (f[' QQQ '))  #不管里面放的啥值, It will get the content of the return value, call is the __getitem__ method f[' name ']= ' Alex ' #修改egon的值为alex, call __setitem__ method # del f[' name '] #删除name, will be an error, indicating in the call __ Delitem__ method call succeeds, it has been deleted, it will be error print (f.name) f1 = Foo () print (f = = F1) # print (f.name) # print (f[0])  #一开始不能这样取值, But provides a __getitem__ method so that you can use the # print (f[1]) # print (f[2])

4.__NEW__ (created)

# Singleton Mode # 4.__new__ Method # Singleton mode: is a design pattern class Singleton:    def __new__ (CLS, *args, **kw): If not        hasattr (CLS, ' _instance ' ):            orig = Super (Singleton, CLS)            cls._instance = orig.__new__ (CLS, *args, **kw)        return cls._instanceone = Singleton () Singleton () print (one,two)   
#__new__
# class a:# def __init__ (self): #有一个方法在帮你创造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 = A () # Print (a,b,c,d)

  

5.__call__

object is appended with parentheses to trigger execution

Note: The execution of the construction method is triggered by the creation object, that is: Object = class name (), and the execution of the __call__ method is triggered by parentheses after the object, i.e.: Object () or Class () ()

Class Foo:    def __call__ (self, *args, **kwargs):        print (123) # f = Foo () # f () #如果不写上面的__call__方法, it is not called. If you add it, it's right. Foo () () #也可以这样表示

6.__len__

7.__hash__

Class Foo:
def __hash__ (self):
Print (' aaaaaaaaaa ')
return Hash (self.name)
# print (' AAAS ')
f = Foo ()
F.name = ' Egon '
Print (hash (f)) #hash方法是可以重写的

8.__eq__

Class A:
def __eq__ (self, Other):
Return True
A = A ()
b = A ()
Print (a==b) #不加方法的时候返回的是False, adding a __eq__ method returns a true
# ' = = ' inside called the __eq__ method
Print (A is B)

A question of a face

# Card game from collections Import Namedtuplecard = Namedtuple (' Card ', [' rank ', ' suit '])  #两个属性: One is number, One is the suit (the object of each card is a card) class Franchdeck: #纸牌数据类型    ranks = [STR (n) for n in range (2,11)] + list (' Jqka ')    suits = [' hearts ', ' square plate ', ' Plum blossom ', ' spades ']    def __init__ (self):        self._cards = [Card (rank,suit) for rank in Franchdeck.ranks #先循环这个, The loop below the loop 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]) # print (deck[0]) # print (deck[0]) # print (deck[0]) from random import choiceprint (choice ( Deck)) Print (choice (deck)) from random import shuffleshuffle (deck) print (Deck[:5])

  

Python full Stack development "17th article" Object-oriented reflection and built-in methods

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.