python 基本类型的创建方法

时间:2022-01-25 13:07:20

1、int

class int(object)
| int(x=0) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal字面 in the
| given base. The literal can be preceded在什么之前 by '+' or '-' and be surrounded环绕
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
 # 1、没有参数转换为0
print(int())
print('*' * 50) # 2、一个数字转换为整数
print(int(10.6))
print('*' * 50) # 3、将一个字符串转换为整数
print(int('', 16))
print(int('', 10))
print(int('', 8))
print(int('', 2))
print('*' * 50) # 4、将一个字节流或字节数组转换为整数
print(int(b'', 16))
print(int(b'', 10))
print(int(b'', 8))
print(int(b'', 2))
print('*' * 50) # 5、base=0时,按字面值进行转换
print(int('0x111', 0))
print(int('', 0))
print(int('0o111', 0))
print(int('0b111', 0))
print('*' * 50)
 0
**************************************************
10
**************************************************
273
111
73
7
**************************************************
273
111
73
7
**************************************************
273
111
73
7
**************************************************

2、bool

class bool(int)
| bool(x) -> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of the class bool.
| The class bool is a subclass of the class int, and cannot be subclassed.

3、float

class float(object)
| float(x) -> floating point number
|
| Convert a string or number to a floating point number, if possible.
 print(float(123))
print(float(''))
 123.0
123.0

4、str

class str(object)
| str(object='') -> str
# 对象转字符串
| str(bytes_or_buffer[, encoding[, errors]]) -> str
# 字节流转字符串
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
 # 1、对象转字符串
# 如果对象存在__str__方法,就调用它,否则调用__repr__
print(str([1, 2, 3])) # 调用了列表的__str__
print([1, 2, 3].__str__())
print(str(type)) # 调用了列表的__repr__
print(type.__repr__(type))
print('*' * 50)
# 注意
print(str(b'')) # 这个是对象转字符串,不是字节流转字符串
print(b''.__str__())
print('*' * 50) # 2、字节流转字符串
# 第一个参数是字节流对象
# 第二个参数是解码方式,默认是sys.getdefaultencoding()
# 第三个参数是转换出错时的处理方法,默认是strict
import sys
print(sys.getdefaultencoding())
print(str(b'', encoding='utf-8')) # 字节流转字符串的第一种方法
# 字节流转换字符串
print(b''.decode(encoding='utf-8')) # 字节流转字符串的第二种方法
 [1, 2, 3]
[1, 2, 3]
<class 'type'>
<class 'type'>
**************************************************
b''
b''
**************************************************
utf-8
123456
123456

5、bytearray

class bytearray(object)
| bytearray(iterable_of_ints) -> bytearray<br>
# 元素必须为[0 ,255] 中的整数
| bytearray(string, encoding[, errors]) -> bytearray<br>
# 按照指定的 encoding 将字符串转换为字节序列
| bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer<br>
# 字节流
| bytearray(int) -> bytes array of size given by the parameter initialized with null bytes<br>
# 返回一个长度为 source 的初始化数组
| bytearray() -> empty bytes array<br>
# 默认就是初始化数组为0个元素
|
| Construct a mutable bytearray object from:
| - an iterable yielding integers in range(256)
# bytearray([1, 2, 3])
| - a text string encoded using the specified encoding
# bytearray('你妈嗨', encoding='utf-8')
| - a bytes or a buffer object
# bytearray('你妈嗨'.encode('utf-8'))
| - any object implementing the buffer API.
| - an integer
# bytearray(10)
 # 1、0个元素的字节数组
print(bytearray())
print('*' * 50) # 2、指定个数的字节数组
print(bytearray(10))
print('*' * 50) # 3、int类型的可迭代对象,值在0-255
print(bytearray([1, 2, 3, 4, 5]))
print('*' * 50) # 4、字符串转字节数组
print(bytearray('', encoding='utf-8'))
print('*' * 50) # 5、字节流转字符串
print(bytearray(b''))
print('*' * 50)
 bytearray(b'')
**************************************************
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
**************************************************
bytearray(b'\x01\x02\x03\x04\x05')
**************************************************
bytearray(b'')
**************************************************
bytearray(b'')
**************************************************

6、bytes

class bytes(object)
| bytes(iterable_of_ints) -> bytes<br> # bytes([1, 2, 3, 4]) bytes must be in range(0, 256)
| bytes(string, encoding[, errors]) -> bytes<br> # bytes('你妈嗨', encoding='utf-8')
| bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer<br> #
| bytes(int) -> bytes object of size given by the parameter initialized with null bytes
| bytes() -> empty bytes object
|
| Construct an immutable array of bytes from:
| - an iterable yielding integers in range(256)
| - a text string encoded using the specified encoding
| - any object implementing the buffer API.
| - an integer
 # 1、一个空字节流
print(bytes())
print('*' * 50) # 2、一个指定长度的字节流
print(bytes(10))
print('*' * 50) # 3、int类型的可迭代对象,值0-255
print(bytes([1, 2, 3, 4, 5]))
print('*' * 50) # 4、string转bytes
print(bytes('', encoding='utf-8'))
print('*' * 50) print(''.encode(encoding='utf-8'))
print('*' * 50) # 5、bytearry转bytes print(bytes(bytearray([1, 2, 3, 4, 5])))
print('*' * 50)
 b''
**************************************************
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
**************************************************
b'\x01\x02\x03\x04\x05'
**************************************************
b''
**************************************************
b''
**************************************************
b'\x01\x02\x03\x04\x05'
**************************************************

7、list

class list(object)
| list() -> new empty list
| list(iterable) -> new list initialized from iterable's items
 # 1、返回一个空列表
print(list()) # 2、将一个可迭代对象转换成列表
print(list('string'))
print(list([1, 2, 3, 4]))
print(list({'one': 1, 'two': 2})) # 3、参数是一个列表
l = [1, 2, 3, 4]
print(id(l))
l2 = list(l) # 创建了一个新的列表,与元组不同
print(id(l2))
 []
['s', 't', 'r', 'i', 'n', 'g']
[1, 2, 3, 4]
['one', 'two']
35749640
35749704

字典转列表:

 d = {'one': 1, 'two': 2}

 for i in d:
print(i)
print('*'*50) for i in d.keys():
print(i)
print('*'*50) for i in d.values():
print(i)
print('*'*50) for i in d.items():
print(i)
print('*'*50) print(list(d))
print(list(d.keys()))
print(list(d.values()))
print(list(d.items()))
print('*'*50) print(d)
print(d.keys())
print(d.values())
print(d.items())
print('*'*50) print(type(d))
print(type(d.keys()))
print(type(d.values()))
print(type(d.items()))
print('*'*50)
 one
two
**************************************************
one
two
**************************************************
1
2
**************************************************
('one', 1)
('two', 2)
**************************************************
['one', 'two']
['one', 'two']
[1, 2]
[('one', 1), ('two', 2)]
**************************************************
{'one': 1, 'two': 2}
dict_keys(['one', 'two'])
dict_values([1, 2])
dict_items([('one', 1), ('two', 2)])
**************************************************
<class 'dict'>
<class 'dict_keys'>
<class 'dict_values'>
<class 'dict_items'>
**************************************************

8、tuple

class tuple(object)
| tuple() -> empty tuple
# 创建一个空的元组
| tuple(iterable) -> tuple initialized from iterable's items
# 将一个可迭代对象转成元组
|
| If the argument is a tuple, the return value is the same object.
# 如果参数时一个元组,返回一个相同的对象
 # 1、返回一个空元组
print(tuple()) # 2、将一个可迭代对象转换成元组
print(tuple('string'))
print(tuple([, , , ]))
print(tuple({'one': , 'two': })) # 3、参数是一个元组
tp = (, , , )
print(id(tp))
tp2 = tuple(tp)
print(id(tp2))
 ()
('s', 't', 'r', 'i', 'n', 'g')
(1, 2, 3, 4)
('one', 'two') # 参数是字典的时候,返回的是键值的元组
35774616
35774616

字典转元组:

 d = {'one': 1, 'two': 2}

 for i in d:
print(i)
print('*'*50) for i in d.keys():
print(i)
print('*'*50) for i in d.values():
print(i)
print('*'*50) for i in d.items():
print(i)
print('*'*50) print(tuple(d))
print(tuple(d.keys()))
print(tuple(d.values()))
print(tuple(d.items()))
print('*'*50) print(d)
print(d.keys())
print(d.values())
print(d.items())
print('*'*50) print(type(d))
print(type(d.keys()))
print(type(d.values()))
print(type(d.items()))
print('*'*50)
one
two
**************************************************
one
two
**************************************************
1
2
**************************************************
('one', 1)
('two', 2)
**************************************************
('one', 'two')
('one', 'two')
(1, 2)
(('one', 1), ('two', 2))
**************************************************
{'one': 1, 'two': 2}
dict_keys(['one', 'two'])
dict_values([1, 2])
dict_items([('one', 1), ('two', 2)])
**************************************************
<class 'dict'>
<class 'dict_keys'>
<class 'dict_values'>
<class 'dict_items'>
**************************************************

9、dict

class dict(object)
| dict() -> new empty dictionary # 空字典
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs<br> # dict([('one', 1), ('two', 2)])
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
 # 1、空字典
print(dict())
print('*' * 50) # 2、从一个映射对象创建字典
print(dict([('one', 1), ('two', 2)]))
print('*' * 50) # 3、从一个带key和value的可迭代对象创建字典
d = {'one': 1, 'two': 2}
dt = {}
for k, v in d.items():
dt[k] = v
print(dt)
print('*' * 50) # 4、以name=value对创建字典
print(dict(one=1, two=2))
 {}
**************************************************
{'one': 1, 'two': 2}
**************************************************
{'one': 1, 'two': 2}
**************************************************
{'one': 1, 'two': 2}

10、set

class set(object)
| set() -> new empty set object
| set(iterable) -> new set object
 # 1、创建空集合
print(set()) # 2、可迭代对象转换为集合
print(set([1, 2, 1, 2]))
 set()      # 空集合这样表示,{}表示字典
{1, 2}

11、frozenset

class frozenset(object)
| frozenset() -> empty frozenset object
| frozenset(iterable) -> frozenset object
|
| Build an immutable unordered collection of unique elements.
# 与set的区别是不可变得
 # 1、创建空集合
print(frozenset()) # 2、可迭代对象转换为集合
fs = frozenset([1, 2, 1, 2])
print(fs) # 3、为set和frozenset对象添加元素
s = set((100, ))
s.add(10)
print(s) fs.add(10)
 frozenset()
frozenset({1, 2})
{10, 100}
Traceback (most recent call last):
File "1.py", line 14, in <module>
fs.add(10)
AttributeError: 'frozenset' object has no attribute 'add'

12、complex

class complex(object)
| complex(real[, imag]) -> complex number
|
| Create a complex number from a real part and an optional imaginary part.
| This is equivalent to (real + imag*1j) where imag defaults to 0.
 print(complex(10))
print(complex(10, 10))
a = 10 + 0j
print(a)
print(a == 10)
 (10+0j)
(10+10j)
(10+0j)
True

13、type

class type(object)
| type(object_or_name, bases, dict)
# 创建一个类
| type(object) -> the object's type
# 查看这个对象的类型
| type(name, bases, dict) -> a new type
#
 # type功能1,判断对象的类型
print(type(int))
print(type()) # type功能2,动态创建类
# 第一个参数是字符串
# 第二个参数是父类的元组
# 第三个参数是属性的字典
class Animal():
pass Dog = type('Dog', (Animal,), {})
dog = Dog() print(type(Dog))
print(type(dog))