In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
1.1 use enumerations
Enumeration based on Enum Class implementation
> fromenum import Enum
> Month = Enum ('Month', (' Jan','Feb', 'Mar',' Apr', 'May',' Jun', 'Jul',' Aug', 'Sep',' Oct', 'Nov',' Dec')
> > for name, member inMonth.__members__.items ():
... Print (name,'= >, member,',', member.value)
...
Jan = > Month.Jan, 1
Feb = > Month.Feb, 2
Mar = > Month.Mar, 3
Apr = > Month.Apr, 4
May = > Month.May, 5
Jun = > Month.Jun, 6
Jul = > Month.Jul, 7
Aug = > Month.Aug, 8
Sep = > Month.Sep, 9
Oct = > Month.Oct, 10
Nov = > Month.Nov, 11
Dec = > Month.Dec, 12
The value property is the int constant that is automatically assigned to the member, and the default count starts at 1.
> Month.Jun
> Month.Jun.value
six
Precise control of enumerated types, custom classes can be derived from Enum
> > from enum import Enum, unique
> @ unique-- the decorator checks for duplicates
... Class Weekday (Enum):
... Sun = 0
... Mon = 1
... Tue = 2
... Wed = 3
... Thu = 4
... Fri = 5
... Sat = 6
...
> > Weekday (1)
> > Weekday (5)
> Weekday ['Sun']
> Weekday.Sun
> Weekday.Sun.value
0
> Weekday (7)
Traceback (most recent call last):
File "", line 1, in
File "/ usr/local/lib/python3.5/enum.py", line 235, in _ _ call__
Return cls.__new__ (cls, value)
File "/ usr/local/lib/python3.5/enum.py", line 470, in _ _ new__
Raise ValueError ("r is not a valid s" (value,cls.__name__))
ValueError: 7 is not a valid Weekday
1.2 use metaclass 1.2.1 type ()
The biggest difference between dynamic and static languages is that the definition of functions and classes is not defined at compile time, but dynamically created at run time.
Define a module for hello.py
Class Hello (object):
Def hello (self, name='world'):
Print ('Hello,% s.'% name)
Called in the python interpreter
> from hello import Hello
> > h = Hello ()
> > h.hello ()
Hello, world.
> print (type (Hello))-- type type
> print (type (h))-- class hello type
The definition of class is created dynamically at run time, and the way to create class is to use the type () function.
> deffn (self, name = 'world'):
... Print ('Hello,% s'% name)
...
> Hello= type ('Hello', (object,), dict (hello = fn))
> > h = Hello ()
> > h.hello ()
Hello, world
> > print (type (Hello))
> > print (type (h))
To create a class object, the type () function passes in three parameters in turn:
The name of the 1.class
two。 The collection of inherited parent classes. Note that Python supports multiple inheritance. If there is only one parent class, don't forget the single element of tuple.
> T = (1)
> > type (T)
> > T = (1,)
> > type (T)
The method name of 3.class is bound to the function. Here we bind the function fn to the method name hello.
1.2.2 metaclass
Metaclass, literally translated as metaclass, the simple explanation is: metaclass is the premise of the class.
First define the metaclass, then create the class, and finally create the instance.
Normally, metaclass is rarely used.
First define ListMetaclass
> class ListMetaclass (type): # metaclass is a template for a class and must be derived from type
... Def _ _ new__ (cls, name, bases, attrs):
... Attrs ['add'] = lambda self, vealue:self.append (value)-definition of the method
... Return type.__new__ (cls, name, bases, attrs)
...
> > >
> class Mylist (list, metaclass = ListMetaclass):
... Pass
...
> > L = Mylist ()
> > L
[]
> > L.add (1)
> > L
[1]
When the Python interpreter creates a MyList, it is created through ListMetaclass.__new__ (); here we can modify the definition of metaclass and add a new method to add new functionality.
The parameters received by the _ _ new__ () method are in turn:
1. The object of the class you are currently going to create
two。 The name of the class
3. A collection of parent classes inherited from the
4. A collection of methods for the class.
1.2.2.1 ORM
It means that this part is difficult to understand.
At the beginning of the introduction to metaclass, it is mentioned that metaclass uses very few scenarios, and the ORM scenario is a typical example. As a DBA, I think this skill needs to be mastered.
The full name of ORM is "Object RelationalMapping", that is, object-relational mapping, which maps a row of a relational database to an object, that is, a class corresponds to a table, so that it is easier to write code and does not have to directly operate the SQL statement.
To write an ORM framework, all classes can only be defined dynamically, because only the consumer can define the corresponding classes according to the structure of the table.
Let's try to write an ORM framework.
The first step in writing the underlying module is to write the calling interface first. For example, if a user uses this ORM framework and wants to define a User class to manipulate the corresponding database table User, we expect him to write code like this:
Class User (Model):
# define the attribute-to-column mapping of a class:
Id = IntegerField ('id')
Name = StringField ('username')
Email = StringField ('email')
Password = StringField ('password')
# create an instance:
U = User (id=12345, name='Michael',email='test@orm.org', password='my-pwd')
# Save to database:
U.save ()
Among them, the parent class Model and attribute types StringField and IntegerField are provided by the ORM framework, and the rest of the magic methods such as save () are done automatically by metaclass. Although the writing of metaclass can be complicated, it is extremely easy for ORM users to use.
Now, let's press the above interface to implement the ORM.
First, define the Field class, which is responsible for saving the field names and field types of the database table:
Class Field (object):
Def _ _ init__ (self, name, column_type):
Self.name = name
Self.column_type = column_type
Def _ str__ (self):
Return'% (self.__class__.__name__, self.name)
On the basis of Field, further define various types of Field, such as StringField,IntegerField and so on:
Class StringField (Field):
Def _ _ init__ (self, name):
Super (StringField, self). _ _ init__ (name, 'varchar (100)')
Class IntegerField (Field):
Def _ _ init__ (self, name):
Super (IntegerField, self). _ _ init__ (name, 'bigint')
The next step is to write the most complex ModelMetaclass:
Class ModelMetaclass (type):
Def _ _ new__ (cls, name, bases, attrs):
If name=='Model':
Return type.__new__ (cls, name, bases, attrs)
Print ('Found model:% s'% name)
Mappings = dict ()
For k, v in attrs.items ():
If isinstance (v, Field):
Print ('Found mapping:% s = = >% s'% (k, v))
Mappings [k] = v
For k in mappings.keys ():
Attrs.pop (k)
Attrs ['_ mappings__'] = mappings # saves the mapping between attributes and columns
Attrs ['_ table__'] = name # assumes that the table name and class name are the same
Return type.__new__ (cls, name, bases, attrs)
And the base class Model:
Class Model (dict,metaclass=ModelMetaclass):
Def _ init__ (self, * * kw):
Super (Model, self). _ init__ (* * kw)
Def__getattr__ (self, key):
Try:
Return self [key]
Except KeyError:
Raise AttributeError (r "'Model' object has no attribute'% s'"% key)
Def _ _ setattr__ (self, key, value):
Self [key] = value
Def save (self):
Fields = []
Params = []
Args = []
For k, v in self.__mappings__.items ():
Fields.append (v.name)
Params.append (?)
Args.append (getattr (self, k, None))
Sql = 'insert into% s (% s) values (% s)'% (self.__table__,','.join (fields),', '.join (params))
Print ('SQL:% s'% sql)
Print ('ARGS:% s'% str (args))
When the user defines a class User (Model), the Python interpreter first looks for metaclass in the definition of the current class User. If it does not find it, it continues to look for metaclass in the parent class Model. If it finds it, it uses the ModelMetaclass of metaclass defined in Model to create the User class, that is, the metaclass can implicitly inherit the subclass, but the subclass itself does not feel it.
In ModelMetaclass, there are several things to do:
Exclude modifications to the Model class
Find all the properties of the defined class in the current class (such as User). If you find a Field attribute, save it to a dict of _ _ mappings__, and delete the Field attribute from the class attribute, otherwise, it is easy to cause runtime errors (the property of the instance will obscure the property of the class with the same name)
Save the table name to _ _ table__, which is simplified to the table name defaults to the class name.
In the Model class, you can define various methods to manipulate the database, such as save (), delete (), find (), update, and so on.
We implemented the save () method to save an instance to the database. Because of the table name, the mapping of attributes to fields, and the collection of attribute values, INSERT statements can be constructed.
Try writing code:
U = User (id=12345, name='Michael',email='test@orm.org', password='my-pwd')
U.save ()
The output is as follows:
Found model: User
Found mapping: email = = >
Found mapping: password = = >
Found mapping: id = = >
Found mapping: name = = >
SQL: insert into User (password,email,username,id) values
ARGS: ['my-pwd',' test@orm.org', 'Michael',12345]
As you can see, the save () method has printed out an executable SQL statement and a list of parameters, and you just need to actually connect to the database and execute the SQL statement to complete the real function.
With less than 100 lines of code, we implemented a compact ORM framework through metaclass.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.