day 30 metaclass deeper understanding, singleton

Metaclass deeper understanding

#type only pass a parameter useful? 
type of print object

#class underlying principle, by instantiating the class type class obtained
DEF the __init __ (Self, name):
the self.name name =
the Person type = ( 'the Person', (Object ,), { 'X':. 1, '__ the init __': __ init__})
P = the Person ( 'LQZ')
Print (the Person .__ dict__ magic)
Print (P .__ dict__ magic)
Print (PX)
is equivalent to
class the Person (Object):
X . 1 =
DEF the __init __ (Self, name):
the self.name name =
P = the Person ( 'LQZ')
Print (the Person .__ dict__ magic)
Print (P .__ dict__ magic)
Print (PX)


#exec execution code string, as explained python is

SS = '' '
X =. 1
Print (X)
' ''
G} = {
L} = {
Exec (SS, G, L)
Print (L)


# custom metaclass:Inheritance of the type
class Mymeta (of the type):
__init __ DEF (self, name, bases, dic):
#self is the Person class (objects)
# In this position, in fact, self Person also said that this class has something inside, something the namespace is already dic
# Therefore, in this place, the namespace may be determined by DIC
. # may be directly through self .__ dict __ / self property to determine
A = dic.get ( 'name')
IF not A:
the raise Exception ( 'no attribute name, not create ')
# DEF the __call __ (Self, args *, ** kwargs):
# Pass

class the Person (= the metaclass that Mymeta): # is equivalent to Person = Mymeta (' Person ', (object,), {...}) Mymeta class instantiation, the three parameters will spread Mymeta __init__ method of
DEF __init __ (Self, name):
self.name = name
the raise Exception ( 'not let you create')


the p-the Person = ( 'LQZ') # automatically trigger the execution of the Person class __init__
summary: You can customize yuan class, override the __init__ method to control the class generated


# by calling the metaclass process control class,Examples of the process of generating the object

class Mymeta (of the type):
DEF __call __ (Self, * args, ** kwargs):
# This method must return an object (class objects), this place returns to what p = Person ( 'lqz') p is what
# returns a true Person object class
# Step: generating a null object
object .__ new __ (self) pass a parameter transfer type, will produce a null object class
#obj Person object class is empty
obj = object .__ new __ ( Self)
Print (Self new__ iS Object .__ .__ new__) True #

# the second step: initialize the object, the initial value into the object
obj is an empty object obj .__ Person class init__ call their binding method, it said Person class in writing __init__ method
obj .__ the init __ (* args, ** kwargs)
# class can also be called
Person .__ the init __ (obj, * args, ** kwargs)
Self .__ the init __ (obj, * args, ** kwargs)
Print (obj.name)
# third step: the return of the object
obj return

class the Person (= the metaclass that Mymeta):
# the Person class ():
DEF the __init __ (Self, name):
the self.name = name
DEF the __call __ (Self, args *, ** kwargs):
Print ( 'XXX')


P = Person ( 'lqz')
Print (p.name)
Print (the p-)
# original understanding Person ( 'lqz') calls the __init__ Person class method
# this position will call metaclass __call__ method, so Person __init__ method is called in __call__ method to complete the initialization of an object
p () __call__ method will bring up class


template: control objects generated
class Mymeta (of the type):
DEF __call __ (Self, * args, kwargs **):
obj = Object .__ __ new new (Self)
obj .__ the init __ (* args, ** kwargs)
return obj

class the Person (the metaclass that = Mymeta):
DEF __init __ (Self, name):
name = the self.name
DEF the __call __ (Self, args *, ** kwargs):
Print ( 'XXX')

P = the Person ( 'LQZ')




deepened portion
Object .__ new__

class the Person ():
DEF the __init __ (Self, name, Age ):
Print ( '__ init__')
the self.name name =
self.age = Age
DEF __new __ (CLS, args *, ** kwargs):
Print ( '__ new__')
# generates an empty object of the Person class
return object .__ new __ ( CLS)

P = the Person ( 'LQZ',. 19)
Print (P)

Object .__ new__ which pass the object class to which the class on the air to give
P = Object .__ new new __ (the Person)
Print (P)

the difference between the __new__ and __init__
__new__ create an empty object
__init__ to initialize an empty object

object .__ new __ (Person): generating an object of the Person class empty
type .__ new __ (cls, name , bases, dic): cls had the class object, there are things
metaclass
__init__: generating a control class, after __new__ is
the __call__: generating object against
__new__: generating class control on the most fundamental, in fact, essentially the most fundamental is not it, is the type of __call__, but we can not control the
#
class Mymeta (type):
DEF __init __ (Self, name, bases, dic):
#self is a Person class, Person class there like a namespace
# Print ( 'XXXXXXX')
# Print (name)
# Print (bases)
# Print (DIC)
# = the self.name 'XXXXXXX'
DEF __new __ (CLS, name, bases, DIC):
# Print (name)
# Print (bases)
# Print (DIC)
# generates an empty object (empty class), there is generated in the class is not empty, there is a class of data
# how to complete the initialization class, and the name, bases, dic these things into
Return new new type .__ __ # (CLS, name, bases, DIC)
DIC2 = { 'attr': {}}
for K, V in dic.items ():
# This is an added, with no class name space of __ attr will put the
IF Not k.startswith ( '__'):
DIC2 [ 'attr'] [K] = V
Print ( '-------', DIC2)
return type .__ new new __ (CLS, name, bases, DIC2)


class the Person (the metaclass that = Mymeta): # = Mymeta the Person (name, bases, dic) call __call __ type of - "internal calls Mymeta .__ new __, -" and the tone Mymeta __init__
School = 'Oldboy'
Age = 10
DEF the __init __ (Self, name, Age):
the self.name name =
self.age = Age


Print (the Person .__ dict__ magic)
Print (Person.attr [ 'School'])
# P = the Person ( 'Nick '

Singleton
Design pattern 23 design patterns 
singleton: the whole process is only an example, all instances of a generation point to the same memory space

Implementation of a method (method of binding by class) mono advantageous 
when a user enters an address and a port, a new instance of an object
when the user does not input address and port, to get each object are the same
class Sql ( ):
_instance = None
DEF the __init __ (Self, Port, Host):
self.port = Port
self.host = Host
@classmethod
DEF get_sigoleton (CLS):
Import Settings
IF Not cls._instance:
cls._instance = CLS (settings.PORT , settings.HOST)
return cls._instance

# get_sigoleton each call to get the same objects are
S1 = Sql.get_sigoleton ()
S2 = Sql.get_sigoleton ()
S3 = Sql.get_sigoleton ()

Print (S1)
Print (S2 )
Print (S3)
S4 = the Sql ( '33306', '192.168.1.1')
Print (S4)

The second method: by decorators
When the user inputs an address and port, a new instance of an object
when the user does not input address and port, to get each object are the same
DEF get_sigoleton (CLS):
#cls this class is Sql
Import Settings
_instance = CLS (Settings .port, settings.HOST)
DEF wrapper (* args, ** kwargs):
IF len (args) = 0 or len (kwargs) = 0:!!
# indicate pass parameters to generate a new object
res = cls (* args , ** kwargs)
return RES
the else:
return _instance
return wrapper

# DEF get_sigoleton (CLS):
# _instance = None
# DEF wrapper (* args, ** kwargs):
! # IF len (args) = 0 or len (kwargs) ! = 0:
## represents a pass parameters to generate a new object
# RES = CLS (* args, ** kwargs)
# return RES
The else #:
# Import Settings
# nonlocal _instance
# IF Not _instance:
# = _instance CLS (settings.PORT, settings.HOST)
# return _instance
# return warpper

@get_sigoleton # Sql among the following parameters will pass, corresponding to: Sql get_sigoleton = (the Sql)
class the Sql ():
DEF the __init __ (Self, Port, Host):
self.port = Port
self.host Host =
# = get_sigoleton the Sql (the Sql)
S1 = the Sql ()
S2 = the Sql ()
S3 = the Sql ( '33306', '192.168.1.1')
S4 = the Sql ( '33306', '192.168.1.1')
Print (S1)
Print (S2)
Print (S3)


third, by metaclasses
input port and when the user addresses instantiating a new object is generated
when the user does not input address and port, to get each object, the same is

Mymeta class (type):
DEF the __init __ (Self, name, bases, DIC):
#self class is Sql
Import Settings
# good to instantiate objects, namespace into classes
self._instance = self (settings.PORT, settings .host)
DEF __call __ (Self, * args, ** kwargs):
#self who is? Sql class is
IF len (args) = 0 or len (kwargs) = 0:!!
Obj = new new Object .__ __ (Self)
obj .__ the init __ (* args, ** kwargs)
return obj
the else:
return self._instance

class Sql ( metaclass = Mymeta): # equivalent of Sql = Mymeta (name, bases, dic) that calls the __init__ Mymeta of which has been put in a class of objects to the namespace
DEF __init __ (Self, Port, Host):
self.port Port =
self.host = Host

Print (the Sql .__ dict__ magic)
S1 = the Sql ()
# call __call__ metaclass
S2 = the Sql ()
S3 = the Sql ( '33306', '192.168.1.1')
Print (S1)
Print (S2)
Print (S3)



of four methods, introduced through the module (module Python natural singleton)

import settings
class Sql():
def __init__(self,port,host):
self.port=port
self.host=host

s1=Sql(settings.PORT,settings.HOST)


def test():
from sigonleton import s1
print(s1.port)
print(s1)
def test2():
from sigonleton import s1 as s2
print(s2)

test()
test2()
from sigonleton import s1
from sigonleton import Sql
s2=Sql(3306,'192.168.1.1')
print(s1)
print(s2)

Guess you like

Origin www.cnblogs.com/wwei4332/p/11460427.html