Object oriented metaclass of

print ( 'metaclass') 
### We now define a class
class Demo:
DEF FUNC (Self):
Pass
## generates instantiate an object
obj = Demo ()
## Show object type, the results show that type of object is the class name of the object belongs
Print (of the type (obj)) # obj = Demo ()

## that this time, if we look at our own definition of this type of class it will be what ??? the results

Print (of the type (Demo))
# the results show that: <class 'of the type'>
# before class call generates an object, whether we can interpret it this way, there is one thing he calls, resulting in this class, Demo = of the type ()

# # Well, this thing, what is it?
## this is what we now have to learn metaclass

# write all your classes by default are generated type
class # generated class called meta-class! ! ! That type is the metaclass

# class three characteristics
"" "
1. class name
2. parent class
3. class namespace
" ""
# eval and Exec
# RES = "" "
# for i in the Range (5):
Print # (i)
# "

Exec # (RES)
# exec and eval code string can be identified and executed, but does not support the logic of the code eval

#
# = class_name 'the User'
# class_bases = (Object,)
# RES = "" "
# = School ' Oldboy '
# DEF the __init __ (Self, name):
# the self.name name =
# DEF FUNC (Self):
# Pass
# "" "
# class_attrs} = {
# Exec (RES, {}, class_attrs)
# = the User type ( class_name, class_bases, class_attrs)
# Print (the User)
# Print (User.school)
# obj = the User ( 'Jason')
# Print (obj.name)
# Print (obj)

class MymetaClass (type):
DEF the __call __ (Self, args *, ** kwargs):
# 1. create an object to the namespace __new__
# 2. to change the name space, lost a bunch of names __init__
# 3. produce good returns out target
# 1.Generates an empty object
Self .__ = __ new new obj (Self)
# instance of the object 2.
Self .__ the init __ (obj, args *, ** kwargs)
# Returns the object 3.
return obj
# Super return () Call .__ __ (* args, ** kwargs )
class Demo (the metaclass that = MymetaClass): # designated Demo metaclass is MymetaClass
Pass
obj = Demo ()
Print (obj)
Print (type (obj))

"" "
<__ main __ Demo Object AT 0x0000022048F083C8.>
<class' __main__. Demo '>


<__ main __ demo Object AT 0x00000170FB1D82B0>.
<class' in __main __ demo'>.
"" "




# table officiating key pair of fields
class MemetaClass (type):
DEF __new __ (CLS, class_name, class_bases, class_attrs):
IF class_name = = 'Userinfo':
The raise TypeError ( 'I do not want a bird you ')
IF' School 'in class_attrs:
class_attrs['school'] = '澳门最大线上赌场开业啦'
class_attrs['table_name'] = 'userinfo'
class_attrs['primary_key'] = 'id'
return type.__new__(cls,class_name,class_bases,class_attrs)
class User(object,metaclass=MemetaClass):
school = 'oldboy'
print(User.__dict__)


Guess you like

Origin www.cnblogs.com/1832921tongjieducn/p/10958688.html