Python 内置函数

Python 内置函数被定义为其功能在 Python 中预定义的函数。python 解释器有几个一直存在的功能。这些功能被称为内置功能。Python 中有几个内置函数,如下所示:

Python abs()

python abs() 函数用于返回一个数字的绝对值。它只需要一个参数,一个要返回绝对值的数字。参数可以是整数和浮点数。如果参数是一个复数,那么,abs () 返回它的大小。

Python abs () 函数示例

py
#  integer number	
integer = -20
print('Absolute value of -40 is:', abs(integer))

# floating number
floating = -20.83
print('Absolute value of -40.83 is:', abs(floating))

输出:

py
Absolute value of -20 is: 20
Absolute value of -20.83 is: 20.83


Python all()

python all() 函数接受一个可迭代对象 (如列表、字典等), 如果传递的 iterable 中的所有项都为真,则返回 true。否则,它返回 False。如果可迭代对象为空,all () 函数将返回 True。

Python all () 函数示例

py
# all values true
k = [1, 3, 4, 6]
print(all(k))

# all values false
k = [0, False]
print(all(k))

# one false value
k = [1, 3, 7, 0]
print(all(k))

# one true value
k = [0, False, 5]
print(all(k))

# empty iterable
k = []
print(all(k))

输出:

py
True
False
False
False
True


Python bin()

python bin() 函数用于返回指定整数的二进制表示。结果总是以前缀 0b 开头。

Python bin () 函数示例

py
x =  10
y = bin(x)
print (y)

输出:

py
0b1010


Python bool()

python bool() 使用标准的真值测试过程将一个值转换为布尔值 (真或假)。

Python bool () 示例

py
test1 = []
print(test1,'is',bool(test1))
test1 = [0]
print(test1,'is',bool(test1))
test1 = 0.0
print(test1,'is',bool(test1))
test1 = None
print(test1,'is',bool(test1))
test1 = True
print(test1,'is',bool(test1))
test1 = 'Easy string'
print(test1,'is',bool(test1))

输出:

py
[] is False
[0] is True
0.0 is False
None is False
True is True
Easy string is True


Python bytes()

python 中的 python bytes() 用于返回一个字节对象。它是 bytearray () 函数的不可变版本。

它可以创建指定大小的空字节对象。

Python bytes () 示例

py
string = "Hello World."
array = bytes(string, 'utf-8')
print(array)

输出:

py
b ' Hello World.'


Python callable()

python 中的一个 python **callable ()** 函数是可以调用的。如果传递的对象看起来是可调用的,这个内置函数检查并返回 true,否则返回 false。

Python callable () 函数示例

py
x = 8
print(callable(x))

输出:

py
False


Python compile()

python compile() 函数以源代码为输入,返回一个代码对象,稍后可以由 exec () 函数执行。

Python compile () 函数示例

py
# compile string source to code
code_str = 'x=5\ny=10\nprint("sum =",x+y)'
code = compile(code_str, 'sum.py', 'exec')
print(type(code))
exec(code)
exec(x)

输出:

py
<class 'code'>
sum = 15


Python exec()

python exec() 函数用于动态执行 python 程序,该程序可以是字符串或目标代码,并且它接受大块代码,这与只接受单个表达式的 eval () 函数不同。

Python exec () 函数示例

py
x = 8
exec('print(x==8)')
exec('print(x+4)')

输出:

py
True
12


Python sum()

顾名思义,python sum() 函数用于获取一个可迭代的,即列表的数字之和。

Python sum () 函数示例

py
s = sum([1, 2,4 ])
print(s)

s = sum([1, 2, 4], 10)
print(s)

输出:

py
7
17


Python any()

如果 iterable 中的任何项目为真,python any() 函数将返回真。否则,它返回 False。

Python any () 函数示例

py
l = [4, 3, 2, 0]                            
print(any(l))

l = [0, False]
print(any(l))

l = [0, False, 5]
print(any(l))

l = []
print(any(l))

输出:

py
True
False
True
False


Python ascii()

python ascii() 函数返回一个包含对象的可打印表示的字符串,并使用 \x,\u 或 \U 转义来转义字符串中的非 ascii 字符。

Python ascii () 函数示例

py
normalText = 'Python is interesting'
print(ascii(normalText))

otherText = 'Pythn is interesting'
print(ascii(otherText))

print('Pyth\xf6n is interesting')

输出:

py
'Python is interesting'
'Pyth\xf6n is interesting'
Pythn is interesting


Python bytearray()

python bytearray() 返回一个 bytearray 对象,可以将对象转换成 bytearray 对象,或者创建一个指定大小的空 bytearray 对象。

Python bytearray () 示例

py
string = "Python is a programming language."

# string with encoding 'utf-8'
arr = bytearray(string, 'utf-8')
print(arr)

输出:

py
bytearray(b'Python is a programming language.')


Python eval()

python eval() 函数解析传递给它的表达式,并在程序中运行 python 表达式 (代码)。

Python eval () 函数示例

py
x = 8
print(eval('x + 1'))

输出:

py
9


Python float()

python float() 函数从数字或字符串中返回一个浮点数。

Python float () 示例

py
# for integers
print(float(9))

# for floats
print(float(8.19))

# for string floats
print(float("-24.27"))

# for string floats with whitespaces
print(float(" -17.19\n"))

# string float error
print(float("xyz"))

输出:

py
9.0
8.19
-24.27
-17.19
ValueError: could not convert string to float: 'xyz'


Python format()

python format() 函数返回给定值的格式化表示。

Python format () 函数示例

py
# d, f and b are a type

# integer
print(format(123, "d"))

# float arguments
print(format(123.4567898, "f"))

# binary format
print(format(12, "b"))

输出:

py
123
123.456790
1100


Python frozenset()

python frozenset() 函数返回一个不可变的 frozenset 对象,该对象用给定 iterable 中的元素初始化。

Python frozenset () 示例

py
# tuple of letters
letters = ('m', 'r', 'o', 't', 's')

fSet = frozenset(letters)
print('Frozen set is:', fSet)
print('Empty frozen set is:', frozenset())

输出:

py
Frozen set is: frozenset({'o', 'm', 's', 'r', 't'})
Empty frozen set is: frozenset()


Python getattr()

python getattr() 函数返回对象的命名属性的值。如果找不到,它将返回默认值。

Python getattr () 函数示例

py
class Details:
age = 22
name = "Phill"

details = Details()
print('The age is:', getattr(details, "age"))
print('The age is:', details.age)

输出:

py
The age is: 22
The age is: 22


Python globals()

python globals() 函数返回当前全局符号表的字典。

一个符号表被定义为一个数据结构,它包含了关于程序的所有必要信息。它包括变量名、方法、类等。

Python globals () 函数示例

py
age = 22

globals()['age'] = 22
print('The age is:', age)

输出:

py
The age is: 22


Python any()

python any() 函数如果 iterable 中的任何项目为真,则返回真,否则返回假。

Python any () 函数示例

py
l = [4, 3, 2, 0]                            
print(any(l))

l = [0, False]
print(any(l))

l = [0, False, 5]
print(any(l))

l = []
print(any(l))

输出:

py
True
False
True
False


Python iter()

python iter() 函数用于返回迭代器对象。它创建一个可以一次迭代一个元素的对象。

Python iter () 函数示例

py
# list of numbers
list = [1,2,3,4,5]

listIter = iter(list)

# prints '1'
print(next(listIter))

# prints '2'
print(next(listIter))

# prints '3'
print(next(listIter))

# prints '4'
print(next(listIter))

# prints '5'
print(next(listIter))

输出:

py
1
2
3
4
5


Python len()

python len() 函数用于返回对象的长度 (项数)。

Python len () 函数示例

py
strA = 'Python'
print(len(strA))

输出:

py
6

Python list()

python list() 用 python 创建一个列表。

Python list () 示例

py
# empty list
print(list())

# string
String = 'abcde'
print(list(String))

# tuple
Tuple = (1,2,3,4,5)
print(list(Tuple))
# list
List = [1,2,3,4,5]
print(list(List))

输出:

py
[]
['a', 'b', 'c', 'd', 'e']
[1,2,3,4,5]
[1,2,3,4,5]


Python locals()

python locals() 方法更新并返回当前本地符号表的字典。

一个符号表被定义为一个数据结构,它包含了关于程序的所有必要信息。它包括变量名、方法、类等。

Python locals () 函数示例

py
def localsAbsent():
return locals()

def localsPresent():
present = True
return locals()

print('localsNotPresent:', localsAbsent())
print('localsPresent:', localsPresent())

输出:

py
localsAbsent: {}
localsPresent: {'present': True}


Python map()

python map() 函数用于将给定的函数应用于 iterable (列表、元组等) 的每个项目后,返回结果列表。).

Python map () 功能示例

py
def calculateAddition(n):
return n+n

numbers = (1, 2, 3, 4)
result = map(calculateAddition, numbers)
print(result)

# converting map object to set
numbersAddition = set(result)
print(numbersAddition)

输出:

py
<map object at 0x7fb04a6bec18>
{8, 2, 4, 6}


Python memoryview()

python memoryview() 函数返回给定参数的 memoryview 对象。

Python memoryview () 函数示例

py
#A random bytearray
randomByteArray = bytearray('ABC', 'utf-8')

mv = memoryview(randomByteArray)

# access the memory view's zeroth index
print(mv[0])

# It create byte from memory view
print(bytes(mv[0:2]))

# It create list from memory view
print(list(mv[0:3]))

输出:

py
65
b'AB'
[65, 66, 67]


Python object()

python **object ()** 返回一个空对象。它是所有类的基础,保存所有类默认的内置属性和方法。

Python object () 示例

py
python = object()

print(type(python))
print(dir(python))

输出:

py
<class 'object'>
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__']


Python open()

python open() 函数打开文件并返回相应的文件对象。

Python open () 函数示例

py
# opens python.text file of the current directory
f = open("python.txt")
# specifying full path
f = open("C:/Python33/README.txt")

输出:

py
Since the mode is omitted, the file is opened in 'r' mode; opens for reading.


Python chr()

Python chr() 函数用于获取一个字符串,该字符串表示一个指向 Unicode 代码整数的字符。例如,chr (97) 返回字符串 “a”。此函数接受整数参数,如果超出指定范围,将引发错误。参数的标准范围是从 0 到 1,114,111。

Python chr () 函数示例

py
# Calling function
result = chr(102) # It returns string representation of a char
result2 = chr(112)
# Displaying result
print(result)
print(result2)
# Verify, is it string type?
print("is it string type:", type(result) is str)

输出:

py
ValueError: chr() arg not in range(0x110000)


Python complex()

Python complex() 函数用于将数字或字符串转换为复数。此方法接受两个可选参数并返回一个复数。第一个参数称为实部,第二个称为虚部。

Python complex () 示例

py
# Python complex() function example
# Calling function
a = complex(1) # Passing single parameter
b = complex(1,2) # Passing both parameters
# Displaying result
print(a)
print(b)

输出:

py
(1.5+0j)
(1.5+2.2j)


Python delattr()

Python delattr() 函数用于从类中删除一个属性。它需要两个参数,第一个是类的对象,第二个是我们想要删除的属性。删除属性后,它在类中不再可用,如果尝试使用类对象调用它,将引发错误。

Python delattr () 函数示例

py
class Student:
id = 101
name = "Pranshu"
email = "pranshu@abc.com"
# Declaring function
def getinfo(self):
print(self.id, self.name, self.email)
s = Student()
s.getinfo()
delattr(Student,'course') # Removing attribute which is not available
s.getinfo() # error: throws an error

输出:

py
101 Pranshu [email protected]
AttributeError: course


Python dir()

Python dir() 函数返回当前局部范围内的名称列表。如果调用方法的对象有一个名为 dir() 的方法,将调用该方法,并且必须返回属性列表。它只接受一个对象类型参数。

Python dir () 函数示例

py
# Calling function
att = dir()
# Displaying result
print(att)

输出:

py
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', 
'__name__', '__package__', '__spec__']


Python divmod()

Python divmod() 函数用来求两个数的余数和商。这个函数接受两个数字参数并返回一个元组。两个参数都是必需的,并且都是数字

Python divmod () 函数示例

py
# Python divmod() function example
# Calling function
result = divmod(10,2)
# Displaying result
print(result)

输出:

py
(5, 0)


Python enumerate()

Python enumerate() 函数返回一个枚举对象。它需要两个参数,第一个是元素序列,第二个是序列的起始索引。我们可以通过循环或 next () 方法按顺序获取元素。

Python enumerate () 函数示例

py
# Calling function
result = enumerate([1,2,3])
# Displaying result
print(result)
print(list(result))

输出:

py
<enumerate object at 0x7ff641093d80>
[(0, 1), (1, 2), (2, 3)]


Python dict()

Python dict() 函数是一个创建字典的构造器。Python 字典提供了三种不同的构造器来创建字典:

  • 如果没有传递参数,它将创建一个空字典。

  • 如果给定了位置参数,将使用相同的键值对创建字典。否则,传递一个可迭代对象。

  • 如果给定了关键字参数,关键字参数及其值将被添加到根据位置参数创建的字典中。

Python dict () 示例

py
# Calling function
result = dict() # returns an empty dictionary
result2 = dict(a=1,b=2)
# Displaying result
print(result)
print(result2)

输出:

py
{}
{'a': 1, 'b': 2}


Python filter()

Python filter() 函数用于获取过滤后的元素。这个函数有两个参数,第一个是函数,第二个是可迭代的。过滤器函数返回可迭代对象的那些元素的序列,对于这些元素,函数返回真值

第一个参数可以是 none ,如果函数不可用并且只返回 true 的元素。

Python filter () 功能示例

py
# Python filter() function example
def filterdata(x):
if x>5:
return x
# Calling function
result = filter(filterdata,(1,2,6))
# Displaying result
print(list(result))

输出:

py
[6]


Python hash()

Python hash() 函数用于获取一个对象的哈希值。Python 使用哈希算法计算哈希值。哈希值是整数,用于在字典查找过程中比较字典键。我们只能哈希下面给出的类型:

Hassable 类型:* bool * int * long * float * string * Unicode * tuple * code 对象。

Python hash () 函数示例

py
# Calling function
result = hash(21) # integer value
result2 = hash(22.2) # decimal value
# Displaying result
print(result)
print(result2)

输出:

py
21
461168601842737174


Python help()

Python help() 函数用于获取调用过程中传递的对象相关的帮助。它接受一个可选参数并返回帮助信息。如果没有给出参数,它会显示 Python 帮助控制台。它在内部调用 python 的帮助函数。

Python help () 函数示例

py
# Calling function
info = help() # No argument
# Displaying result
print(info)

输出:

py
Welcome to Python 3.5's help utility!


Python min()

Python min() 函数用于从集合中获取最小的元素。这个函数接受两个参数,第一个是元素的集合,第二个是 key,并返回集合中最小的元素。

Python min () 函数示例

py
# Calling function
small = min(2225,325,2025) # returns smallest element
small2 = min(1000.25,2025.35,5625.36,10052.50)
# Displaying result
print(small)
print(small2)

输出:

py
325
1000.25


Python set()

在 python 中,集合是一个内置类,这个函数是这个类的构造器。它用于使用调用期间传递的元素创建新的集合。它将一个可迭代对象作为参数,并返回一个新的 set 对象。

Python set () 函数示例

py
# Calling function
result = set() # empty set
result2 = set('12')
result3 = set('javatpoint')
# Displaying result
print(result)
print(result2)
print(result3)

输出:

py
set()
{'1', '2'}
{'a', 'n', 'v', 't', 'j', 'p', 'i', 'o'}


Python hex()

Python hex() 函数用于生成一个整数参数的 hex 值。它接受一个整数参数,并返回一个转换为十六进制字符串的整数。在这种情况下,我们希望得到一个浮点的十六进制值,然后使用 float.hex () 函数。

Python hex () 函数示例

py
# Calling function
result = hex(1)
# integer value
result2 = hex(342)
# Displaying result
print(result)
print(result2)

输出:

py
0x1
0x156


Python id()

Python id() 函数返回一个对象的标识。这是一个整数,保证是唯一的。该函数将一个参数作为一个对象,并返回一个代表身份的唯一整数。具有非重叠生存期的两个对象可能具有相同的 id () 值。

Python id () 函数示例

py
# Calling function
val = id("Javatpoint") # string object
val2 = id(1200) # integer object
val3 = id([25,336,95,236,92,3225]) # List object
# Displaying result
print(val)
print(val2)
print(val3)

输出:

py
139963782059696
139963805666864
139963781994504


Python setattr()

Python setattr() 函数用于为对象的属性设置一个值。它接受三个参数,即一个对象、一个字符串和一个任意值,并且不返回任何值。当我们想给一个对象添加一个新的属性并给它设置一个值时,这是很有帮助的。

Python setattr () 函数示例

py
class Student:
id = 0
name = ""

def __init__(self, id, name):
self.id = id
self.name = name

student = Student(102,"Sohan")
print(student.id)
print(student.name)
#print(student.email) product error
setattr(student, 'email','sohan@abc.com') # adding new attribute
print(student.email)

输出:

py
102
Sohan
[email protected]


Python slice()

Python slice() 函数用于从元素集合中获取元素的切片。Python 提供了两个重载切片函数。第一个函数接受单个参数,而第二个函数接受三个参数并返回一个 slice 对象。这个切片对象可以用来获取集合的一个子部分。

Python slice () 函数示例

py
# Calling function
result = slice(5) # returns slice object
result2 = slice(0,5,3) # returns slice object
# Displaying result
print(result)
print(result2)

输出:

py
slice(None, 5, None)
slice(0, 5, 3)


Python sorted()

Python sorted() 函数用于排序元素。默认情况下,它按升序排序元素,但也可以按降序进行排序。它接受四个参数,并按排序顺序返回一个集合。就字典而言,它只排序键,而不排序值。

Python sorted () 函数示例

py
str = "javatpoint" # declaring string
# Calling function
sorted1 = sorted(str) # sorting string
# Displaying result
print(sorted1)

输出:

py
['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']


Python next()

Python next() 函数用于从集合中获取下一项。它接受两个参数,即迭代器和默认值,并返回一个元素。

这个方法调用迭代器,如果没有项目,就会抛出一个错误。为了避免错误,我们可以设置一个默认值。

Python next () 函数示例

py
number = iter([256, 32, 82]) # Creating iterator
# Calling function
item = next(number)
# Displaying result
print(item)
# second item
item = next(number)
print(item)
# third item
item = next(number)
print(item)

输出:

py
256
32
82


Python input()

Python input() 函数用于获取用户的输入。它提示用户输入并读取一行。读取数据后,它将其转换为字符串并返回。如果读取电渗流,它会抛出一个错误 EOFError

Python input () 函数示例

py
# Calling function
val = input("Enter a value: ")
# Displaying result
print("You entered:",val)

输出:

py
Enter a value: 45
You entered: 45


Python int()

Python int() 函数用于获取整数值。它返回一个转换成整数的表达式。如果参数是浮点型的,转换会截断数字。如果参数在整数范围之外,则它会将数字转换为长类型。

如果数字不是数字或者给定了基数,则该数字必须是字符串。

Python int () 函数示例

py
# Calling function
val = int(10) # integer value
val2 = int(10.52) # float value
val3 = int('10') # string value
# Displaying result
print("integer values :",val, val2, val3)

输出:

py
integer values : 10 10 10


Python isinstance()

Python isinstance() 函数用于检查给定的对象是否是该类的实例。如果对象属于该类,它将返回 true。否则返回假。如果类是子类,它也会返回 true。

isinstance() 函数接受两个参数,即对象和 classinfo,然后返回 True 或 False。

Python isinstance () 函数示例

py
class Student:
id = 101
name = "John"
def __init__(self, id, name):
self.id=id
self.name=name

student = Student(1010,"John")
lst = [12,34,5,6,767]
# Calling function
print(isinstance(student, Student)) # isinstance of Student class
print(isinstance(lst, Student))

输出:

py
True
False


Python oct()

Python oct() 函数用于获取一个整数的八进制值。此方法接受一个参数,并返回一个转换为八进制字符串的整数。如果参数类型不是整数,它会抛出一个错误类型错误

Python oct () 函数示例

py
# Calling function
val = oct(10)
# Displaying result
print("Octal value of 10:",val)

输出:

py
Octal value of 10: 0o12


Python order()

python**order ()** 函数返回一个整数,代表给定 Unicode 字符的 Unicode 代码点。

Python order () 函数示例

py
# Code point of an integer
print(ord('8'))

# Code point of an alphabet
print(ord('R'))

# Code point of a character
print(ord('&'))

输出:

py
56
82
38


Python pow()

python pow() 函数用于计算一个数的幂。它返回 x 的 y 次方,如果给定第三个自变量 (z),它返回 x 的 y 模 z 次方,即 (x,y) % z。

Python pow () 函数示例

py
# positive x, positive y (x**y)
print(pow(4, 2))

# negative x, positive y
print(pow(-4, 2))

# positive x, negative y (x**-y)
print(pow(4, -2))

# negative x, negative y
print(pow(-4, -2))

输出:

py
16
16
0.0625
0.0625


Python print()

python print() 函数将给定对象打印到屏幕或其他标准输出设备上。

Python print () 功能示例

py
print("Python is programming language.")

x = 7
# Two objects passed
print("x =", x)

y = x
# Three objects passed
print('x =', x, '= y')

输出:

py
Python is programming language.
x = 7
x = 7 = y


Python range()

python range() 函数返回一个不可变的数字序列,默认情况下从 0 开始,递增 1 (默认情况下),以指定的数字结束。

Python range () 函数示例

py
# empty range
print(list(range(0)))

# using the range(stop)
print(list(range(4)))

# using the range(start, stop)
print(list(range(1,7 )))

输出:

py
[]
[0, 1, 2, 3]
[1, 2, 3, 4, 5, 6]


Python reversed()

python reversed() 函数返回给定序列的反向迭代器。

Python reversed () 函数示例

py
# for string
String = 'Java'
print(list(reversed(String)))

# for tuple
Tuple = ('J', 'a', 'v', 'a')
print(list(reversed(Tuple)))

# for range
Range = range(8, 12)
print(list(reversed(Range)))

# for list
List = [1, 2, 7, 5]
print(list(reversed(List)))

输出:

py
['a', 'v', 'a', 'J']
['a', 'v', 'a', 'J']
[11, 10, 9, 8]
[5, 7, 2, 1]


Python round()

python round() 函数对一个数字的数字进行舍入,并返回浮点数。

Python round () 函数示例

py
#  for integers
print(round(10))

# for floating point
print(round(10.8))

# even choice
print(round(6.6))

输出:

py
10
11
7


Python issubclass()

如果对象参数 (第一个参数) 是第二个类 (第二个参数) 的子类,python issubclass() 函数返回 true。

Python issubclass () 函数示例

py
class Rectangle:
def __init__(rectangleType):
print('Rectangle is a ', rectangleType)

class Square(Rectangle):
def __init__(self):
Rectangle.__init__('square')

print(issubclass(Square, Rectangle))
print(issubclass(Square, list))
print(issubclass(Square, (list, Rectangle)))
print(issubclass(Rectangle, (list, Rectangle)))

输出:

py
True
False
True
True


Python str()

python str() 将指定的值转换为字符串。

Python str () 函数示例

py
str('4')

输出:

py
'4'

Python tuple()

python tuple() 函数用于创建 tuple 对象。

Python tuple () 函数示例

py
t1 = tuple()
print('t1=', t1)

# creating a tuple from a list
t2 = tuple([1, 6, 9])
print('t2=', t2)

# creating a tuple from a string
t1 = tuple('Java')
print('t1=',t1)

# creating a tuple from a dictionary
t1 = tuple({4: 'four', 5: 'five'})
print('t1=',t1)

输出:

py
t1= ()
t2= (1, 6, 9)
t1= ('J', 'a', 'v', 'a')
t1= (4, 5)


Python type()

python **type ()** 返回指定对象的类型,如果单个参数被传递给内置函数的类型 ()。如果传递了三个参数,那么它将返回一个新的类型对象。

Python type () 函数示例

py
List = [4, 5]
print(type(List))

Dict = {4: 'four', 5: 'five'}
print(type(Dict))

class Python:
a = 0

InstanceOfPython = Python()
print(type(InstanceOfPython))

输出:

py
<class 'list'>
<class 'dict'>
<class '__main__.Python'>


Python vars()

python vars() 函数返回给定对象的 dict 属性。

Python vars () 函数示例

py
class Python:
def __init__(self, x = 7, y = 9):
self.x = x
self.y = y

InstanceOfPython = Python()
print(vars(InstanceOfPython))

输出:

py
{'y': 9, 'x': 7}


Python zip()

python zip() 函数返回一个 zip 对象,该对象映射多个容器的相似索引。它接受 iterables (可以为零或更多),使其成为迭代器,根据传递的 iterables 聚合元素,并返回元组的迭代器。

Python zip () 函数示例

py
numList = [4,5, 6]
strList = ['four', 'five', 'six']

# No iterables are passed
result = zip()

# Converting itertor to list
resultList = list(result)
print(resultList)

# Two iterables are passed
result = zip(numList, strList)

# Converting itertor to set
resultSet = set(result)
print(resultSet)

输出:

py
[]
{(5, 'five'), (4, 'four'), (6, 'six')}

原文:https://www.javatpoint.com/python-built-in-functions