This article mainly introduces Python common factory function usage, briefly describes the function of the factory function, defines and unifies the concrete instance form to analyze the Python common factory function The related use skill, needs the friend can refer, hoped can help everybody.
Factory function: a built-in function that can produce an instance of a class.
Factory functions Refer to these built-in functions as class objects that, when called, actually create a class instance.
Examples of factory functions in Python are as follows:
1 "int (), long (), float (), complex (), BOOL ()
>>> A=int (9.9) >>> a9>>> B=long ($) >>> b45l>>> f=float (8) >>> F8.0>>> C=complex (8) >>> C (8+0j) >>> b1=bool (7.9) >>> b1true>>> B2=bool ( 0.0) >>> b2false>>> b3=bool ([]) >>> b2false>>> b4=bool ((34,5)) >>> b4true
2 "str (), Unicode ()
>>> s=str (9.9) >>> s ' 9.9 ' >>> Unicode (9.0) U ' 9.0 ' >>> Unicode (' Love ') U ' Love '
3 "list (), tuple (): Generate lists or tuples
>>> l=list (' python ') >>> l[' P ', ' y ', ' t ', ' h ', ' o ', ' n ']>>> t=tuple (' python ') >>> t (' P ', ' y ', ' t ', ' h ', ' o ', ' n ')
4 "type (): View type
>>> type (6) <type ' int ' >>>> type (' python ') <type ' str ' >>>> type (U ' love ') < Type ' Unicode ' >>>> class A (): ... Pass...>>> a=a () >>> type (a) <type ' instance ' >>>> type (a) <type ' classobj ' >
5 "dict (): Generate a dictionary
>>> dict () {}>>> dict (one=1,two=2) {' One ': 2, ' one ': 1}>>> dict ((' One ', ' one ', ') ') {' Both ': 2, ' one ': 1}>>> dict ([' One ', 1], (' One ', 2)]) {' One ': 2, ' one ': 1}>>> dict ([[' One ', ' 1],[', 2]]) {' One ': 2, ' one ': 1}>>> dict ((' One ', 1), (' One ', 2) ') {' One ': 2, ' one ': 1}>>> dict ([' One ', ' 1],[', 2] ) {' One ': 2, ' One ': 1}
6 Set (): Production of variable sets
>>> s=set (' python ') >>> sset ([' H ', ' o ', ' n ', ' P ', ' t ', ' y ']) >>> s.add (825) #可变集合 >>> Sset ([' H ', ' o ', ' n ', ' P ', ' t ', ' Y ', 825])
7 "Frozenset (): Creating Immutable Collections
>>> s=frozenset (' python ') >>> sfrozenset ([' H ', ' o ', ' n ', ' P ', ' t ', ' y ']) >>> S.add () # Immutable collection Attributeerror: ' Frozenset ' object has no attribute ' add '