10, Python full Stack Road-object-oriented advanced

Source: Internet
Author: User

10. Object-oriented Advanced

Http://www.cnblogs.com/Eva-J/articles/7351812.html

1,isinstance and issubclass 1.1 isinstance (OBJ,CLS)

Isinstance (OBJ,CLS) checks if obj is an object of class CLS

1.2 Issubclass (sub, super)

Issubclass (Sub, super) check if the sub class is a derived class of super class

2. Reflection

# turn A variable of a string data type into a variable name that actually exists in the program and be able to use it

#getattr is the reflection of the soul

#hasatte and getattr are the best CP

# Class Name Properties or methods (static ( class ) Properties, static methods, and class methods)

# Object Name Tune property or method (object properties, Normal method (self))

# Module Name Call property or method (variable, function)

# Call a property or method (variable, function) in your own module

# own module means : sys.modules[__name__]

# # #setattr

# # #delattr

2.1 getter ()

GetAttr ( object , ' method name, or attribute name '), which calls the method directly using this function without invoking the method of the class

2.2 hasattr ()

Hasattr ( object , ' method name, or property name ') determines whether this method or property returns a Boolean value in the object

If the method does not exist will be an error, this time we need to use hasattr to make judgments

if hasattr (Jinghong,' Sleep '):
Func = GetAttr (Jinghong,' sleep ')
Func ()

2.3 setattr ()

Setting properties

2.4 delattr ()

2.5 Class name Tune property or method

Static ( class ) properties, static methods, and class methods

2.6 Object Name Tune property or method

object Properties, Normal method (self)

2.7 Module Name Call property or method

variables, functions

2.8 Calling a property or method in its own module

variables, functions

# own module means : sys.modules[__name__]

3 , the built-in method of the class

The built-in methods and built-in functions of #python classes are inextricably linked with other functions .

3.1 __str__ and __repr__

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
}

classSchool:
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 notFormat_specorFormat_spec not inFormat_dict:
Format_spec =' Nat '
        FMT = Format_dict[format_spec]
returnFmt.format (obj=self)

S1 = School (' oldboy1 ',' Beijing ',' Private ')
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 the __str__ is not defined, then the __repr__ will be used instead of the output
Note : The return value of both methods must be a string or throw an exception
" "
Print (Format (S1,' Nat '))
Print (Format (S1,' TNA '))
Print (Format (S1,' Tan '))
Print (Format (S1,' Asfdasdffd '))

class B:
def __str__ (self):
return ' Str:class B '

def __repr__ (self):
return ' Repr:class B '

b = B ()
Print ('%s ' % b)
Print ('%r ' % b)

3.2 __del__

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

3.3 __getitem__\__setitem__\__delitem__

classFoo:
def__init__ (Self,name):
Self.name=name

def__getitem__ (self, item):
Print (Self.__dict__[item])

def__setitem__ (self, Key, value):
Self.__dict__[key]=value
def__delitem__ (self, key):
Print' del Obj[key], when I executed ')
Self.__dict__.pop (Key)
def__DELATTR__ (self, item):
Print' del obj.key when I do ')
Self.__dict__.pop (item)

F1=foo (' SB ')
f1[' age ']=18
f1[' Age1 ']=19
delF1.age1
delf1[' age ']
f1[' name ']=' Alex '
Print (f1.__dict__)

3.4 __new__ 3.4.1 __new__

class A:
def __init__ (self):
self.x = 1
Print (' in init function ')
def __new__ (CLS, *args, **kwargs):
Print (' in new function ')
return object.__new__ (A, *args, **kwargs)

A = A ()
Print (a.x)

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._instance

one = Singleton ()
both = Singleton ()

TWO.A = 3
Print (ONE.A)
# 3
# One and both are exactly the same, can be detected with ID (), = =, is
Print (ID (one))
# 29097904
Print (ID ())
# 29097904
Print (one = =)
# True
Print (one is)

3.4.2 Single-case mode

# Singleton pattern Instances There is always only one of his attributes can change as you change

classTeacher:#创建一个老师类
    __isinstance =None#创建一个私有静态变量来装裸着的对象
    def__new__ (CLS, *args, **kwargs):#创建一个裸着的对象
        if notCls.__isinstance:#如果__isinstance属性为None
            Cls.__isinstance = object.__new__ (CLS)#用object. __new__ Create a Bare object
        returnCls.__isinstance#返回一个对象

    def__init__ (Self,name,cloth):#self就是cls. __isinstance objects returned by
        Self.name = Name#给self的name属性赋值
        Self.cloth = Cloth#给self的cloth属性赋值

Mr. Liu= Teacher (' Liu Yongji ',' White ')
Print (teacher Liu. Name)
Miss Wang= Teacher (' Wang Qing handsome ',' Black ')
Miss Wang2 = Teacher (' Wang Qing handsome ',' Black ')
Miss Wang3 = Teacher (' Wang Qing handsome ',' Black ')
Miss Wang4 = Teacher (' Wang Qing handsome ',' Black ')
Print (teacher Liu. Name)
Print (Miss Wang)
Print (Mr. Wang 2)
Print (Mr. Wang 3)
Print (Mr. Wang 4)

3.5 __call__

The object is appended with parentheses to trigger execution.

class Foo:
def __init__ (self):
Pass

def __call__ (self, *args, **kwargs):
Print (' __call__ ')

obj = Foo () # execution __init__
obj () # execution __call__

3.6 __len__

class A:
def __init__ (self):
SELF.A = 1
SELF.B = 2

def __len__ (self):
return len (self.__dict__)
A = A ()
Print (Len (a))

3.7 __hash__

class A:
def __init__ (self):
SELF.A = 1
SELF.B = 2

def __hash__ (self):
return hash (str (SELF.A) +str (self.b))
A = A ()
Print (hash (a))

3.8 __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 True
A = A ()
b = A ()
Print (A = = b)

3.9 face question

# There is a class for the init method as follows:

# class Person:

# def __init__ (self,name,age,sex,weight):

# self.name = Name

# self.sex = Sex

# Self.age = Age

# self.weight = Weight

# Suppose there 's an object for a person ,

# if the name and sex attributes of the obj1,obj2 of two objects are the same

# that is obj1.name==obj2.name and Obj1.sex==obj2.sex

# We think that the two objects are the same object, and we know that each of the four objects in the list is going to go to the same object .

# Hint:

# Two built-in methods to override the person class weight

classPerson:
def__init__ (self,name,sex,age):
Self.name = Name
Self.sex = Sex
Self.age = Age

def__hash__ (self):
returnHash (Self.name+self.sex)

def__eq__ (self, Other):
offSelf.name = = Other.name andSelf.sex = = Other.sex:
return True
Obj_lst = []
forIinchRange (100):
Obj_lst.append (Person (' Liquan ',' Male ', i))
Print (OBJ_LST)
Print (Set (OBJ_LST))#unhashable

10, Python full Stack Road-object-oriented advanced

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.