This article mainly introduces the usage of common factory functions in Python. It briefly describes the functions and definitions of factory functions and analyzes the related usage skills of common factory functions in Python based on specific examples. Friends who need it can refer to it. I hope it can help. to everyone.
Factory function: Built-in function that can generate class instances.
Factory function means that these built-in functions are all class objects. When they are called, a class instance is actually created.
Examples of factory functions in python are as follows:
1》int(),long(),float(),complex(),bool()
>>> a=int(9.9) >>> a 9 >>> b=long(45) >>> b 45L >>> f=float(8) >>> f 8.0 >>> c=complex(8) >>> c (8+0j) >>> b1=bool(7.9) >>> b1 True >>> b2=bool(0.0) >>> b2 False >>> b3=bool([]) >>> b2 False >>> b4=bool((34,5)) >>> b4 True
2》str(),unicode()
>>> s=str(9.9) >>> s '9.9' >>> unicode(9.0) u'9.0' >>> unicode('love') u'love'
3》list(), tuple(): Generate list or tuple
##
>>> 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) {'two': 2, 'one': 1} >>> dict(zip(('one','two'),(1,2))) {'two': 2, 'one': 1} >>> dict([('one',1),('two',2)]) {'two': 2, 'one': 1} >>> dict([['one',1],['two',2]]) {'two': 2, 'one': 1} >>> dict((('one',1),('two',2))) {'two': 2, 'one': 1} >>> dict((['one',1],['two',2])) {'two': 2, 'one': 1}
6》 set(): Produce a mutable collection
##
>>> s=set('python') >>> s set(['h', 'o', 'n', 'p', 't', 'y']) >>> s.add(825)#可变集合 >>> s set(['h', 'o', 'n', 'p', 't', 'y', 825])
Related recommendations: The above is the detailed content of Detailed explanation of common factory function usage in Python. For more information, please follow other related articles on the PHP Chinese website!>>> s=frozenset('python')
>>> s
frozenset(['h', 'o', 'n', 'p', 't', 'y'])
>>> s.add()#不可变集合
AttributeError: 'frozenset' object has no attribute 'add'