Python Full Stack Development * 23 Object-oriented Knowledge points summary * 180704

Source: Internet
Author: User

23 Object-oriented
      -----Special Methods



1. Isinstance (obj, class name)     determines whether an object is instantiated as such or instantiated by subclasses of this class.
Class A:pass
Class B (A):p
B1=b ()
Print (isinstance(b1,b)) # True
Print (isinstance(b1,a)) # True
2.issubclass (class name, class name 1) determine if the class name is a subclass of class name 1
Class A:pass
Class B (A):p
Print (issubclass(b,a)) #True
Print (issubclass(b)) #False

3.__len__ Usage
class C:
def __init__ (self):
self.a=1
self.b=2
def __len__ (self):
return len (self.__dict__)
c1=c ()
Print(len (C1))
4.__hash__ Usage
class C:
def __init__ (self):
self.a=1
self.b=2
def __hash__ (self):
return Hash (str (SELF.A) +str (self.b))
c1=c ()
Print (hash (c1))
5.__str__ Usage If the __str__ method is defined in a class, the return value of the method is output by default when the object is printed
class B:
def __init__ (self,name,age):
Self.name=name
Self.age=age
def __repr__ (self):
return "Taibai"
b2=b ("alex1", +)
print (B2)
Print ("%s"% B2)

6.__repr__ Usage If the __repr__ method is defined in a class, the return value of the method is output by default when Repr (object)
class B:
def __init__ (self,name,age):
Self.name=name
Self.age=age
def __repr__ (self):
print ("666")
return "Taibai"
b1=b ("Alex", +)
Print (repr (B1)) # method One
Print ("%r"% B1) # method Two
#补充知识: Formatted output
#%s number and string%r + "" repr true Colours%d number%f decimal
The execution of the 7.__CALL__ usage construction method is triggered by the creation object, that is: Object = class name (), and the execution of the __call__ method is triggered by parentheses behind the object .
that is: Object () or Class () ( )
class Foo:
def __init__ (self):
Pass
def __call__ (Self,*args,**kwargs):
print (Args,kwargs)
A1=foo ()
A1 ("Alex", a=666) # (' Alex ',) {' A ': 666}

The 8.__eq__ usage automatically triggers when a class instantiates two objects for comparison operations.
class A:
def __init__ (self,):
self.a=1
self.b=2
def __eq__ (self,obj): # Need to manually pass a parameter
if Self.a==obj.a and self.b==obj.b:
return True
a1=a ()
b1=a ()
print (a1==b1)
9.__del__ Usage Analysis Method
#Python garbage collection mechanism :
#文件中你创建的所有的变量, class, and so on, all variables, classes are marked during execution, and after execution, they are automatically reclaimed for a period of time without being called.
class A:
def __del__ (self):
print ("666")
a1=a ()
a1.__del__

10.__new__ Usage
class A:
def __init__ (self):
self.x=1
print ("in init function") # Fifth Step
def __new__ (Cls,*args,**kwargs): # The second step automates the __new__ method
print (CLS) # Third Step <class ' __main__. A ' >
print ("in new Function") # Fourth Step

return super (). __new__ (CLS) # Returns an object space
return object.__new__ (CLS) the second method
A1=a () # First step class name parentheses
11. Design mode:
Singleton mode: Only one object can be instantiated on a class. The simplest design pattern, ( interview must test )
class A:
__instance=none
def __new__ (CLS, *argsm, **kwargs):
if A.__instance is None:
obj=object.__new__ (CLS)
A.__instance=obj
return a.__instance
a1=a ()
b1=a ()
c1=a ()
print (A1,B1,C1)
12.item Usage
class Foo:
def __init__ (self,name):
Self.name=name
def __getitem__ (self,item):
if Hasattr (self,item):
return GetAttr (Self,item)
Else:
print ("No this variable")
def __SetItem__ (self,key,value):
print (Key,value)
def __delitem__ (self,key):
print (key)

F1=foo ("Alex")
Print (f1["name"])
f1["name"]= "Mary"
del f1["name"]

Python Full Stack Development * 23 Object-oriented Knowledge points summary * 180704

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.