Python-内置函数

1.abs(x):返回数字的绝对值,x可以是整数、浮点数、复数;注:若x是复数,则返回其大小import matha = -1b = -1.3232c = bd = 1+1.0je = 3+4.0jf="a"g=[1,2]print ("a的绝对值是:",abs(a)) # 1print("b的绝对值是:",abs(b)) # 1.3232print("c的...
摘要由CSDN通过智能技术生成

 

1.abs(x):返回数字的绝对值,x可以是整数、浮点数、复数;

注:若x是复数,则返回其大小

import math
a = -1
b = -1.3232
c = b
d = 1+1.0j
e = 3+4.0j
f="a"
g=[1,2]
print ("a的绝对值是:",abs(a))  # 1
print("b的绝对值是:",abs(b))  # 1.3232
print("c的绝对值是:",math.fabs(c))  # 1.3232
print("d的的绝对值是:",abs(d))  # 1.4142135623730951
# print("e的绝对值是:",math.fabs(e))  # 报错:TypeError: can't convert complex to float
# print("f的的绝对值是:",abs(f))  # 报错:TypeError: bad operand type for abs(): 'str'
# print("g的的绝对值是:",abs(g))  # 报错:TypeError: bad operand type for abs(): 'list'

2.all(iterable):(1)iterable非空的前提下,并且iterable里的元素全为true,则返回True,否则返回False;(2)iterable为空,则返回True

print(all(["a",[2,3],1,True]))  # True
print(all(["a",[],1,True]))  # False
print(all(["a",[2,3],0,True]))  # False
print(all(["a",[2,3],10,False]))  # False

print(all(("a",[2,3],1,True)))  # True
print(all(("a",[],1,True)))  # False
print(all(("a",[2,3],0,True)))  # False
print(all(("a",[2,3],10,False)))  # False

print(all("dsajf"))  # True
# print(all(12345))  # 报错:TypeError: 'int' object is not iterable
print(all([1,2,3]))  # True


print(all([]))  # True
print(all(()))  # True
print(all({}))  # True
print(all(""))  # True

3.any(iterable):(1)iterable非空的前提下,并且iterable里的元素只要有1个为true,则返回True,否则返回False;(2)iterable为空,则返回False

print(any(["a",[2,3],1,True]))  # True
print(any(["a",[],1,True]))  # True
print(any(["a",[2,3],0,True]))  # True
print(any(["a",[2,3],10,False]))  # True

print(any(("a",[2,3],1,True)))  # True
print(any(("a",[],1,True)))  # True
print(any(("a",[2,3],0,True)))  # True
print(any(("a",[2,3],10,False)))  # True

print(any("dsajf"))  # True
# print(all(12345))  # 报错:TypeError: 'int' object is not iterable
print(any([1,2,3]))  # True


print(any([]))  # False
print(any(()))  # False
print(any({}))  # False
print(any(""))  # False

4.ascii(obj):返回一个对象可打印的字符串,与repr(obj)略有区别, repr() 返回的字符串中非 ASCII 编码的字符,会使用 \x、\u 和 \U 来转义,而ascii()不会

print(ascii(1))  # 1
print(ascii("1"))  # '1'
print(ascii("a"))  # 'a'
print(ascii([1,2,3]))  # [1, 2, 3]
print(ascii((2,3,4)))  # (2, 3, 4)
print(ascii("点击"))  # '\u70b9\u51fb'

print(repr(1))  # 1
print(repr("1"))  # '1'
print(repr("a"))  # 'a'
print(repr([1,2,3]))  # [1, 2, 3]
print(repr((2,3,4)))  # (2, 3, 4)
print(repr("点击"))  # '点击'

5.bin(x):将一个整数转变为一个前缀为“0b”的二进制字符串

print(bin(1))  # 0b1
# print(bin(1.1))  # 报错:TypeError: 'float' object cannot be interpreted as an integer
print(bin(0))  # 0b0
# print(bin(0.0))  # 报错:TypeError: 'float' object cannot be interpreted as an integer
print(bin(-2))  # -0b10
# print(bin("a"))  # 报错:TypeError: 'str' object cannot be interpreted as an integer

6.bool(x):返回一个布尔值,True 或者 False。如果 x 是假的或者被省略,返回 False;其他情况返回 True。bool 类是 int 的子类,其他类不能继承自它,它只有 False 和 True 两个实例。在 3.7 版中,x 现在只能作为位置参数。

print(bool(0))  # False
print(bool(0.0))  # False
print(bool(1))  # True
print(bool(1.1))  # True
print(bool())  # False
print(bool(()))  # False
print(bool([]))  # False
print(bool(None))  # False
print(bool(1.1))  # True
print(bool(True))  # True
print(bool(False))  # False
print(bool(0+0j))  # False
print(bool(set()))  # False
print(bool(range(0)))  # False
print(bool("a"))  # True
print(bool)  # <class 'bool'>
print(True)  # True
print(True+1)  # 2
print(False)  # False
print(False+1)  # 1

7.breakpoint(*args, **kws):运行到此函数时,会陷入到调试器中。实际调用的是 sys.breakpointhook() ,直接传递 args 和 kws 。默认情况下, sys.breakpointhook() 调用 pdb.set_trace() 且没有参数。

def test_ic(favourite_ic):
    user_guess = input("Try to guess our favourite IC >>> ")
    breakpoint()

    if user_guess == favourite_ic:
        return "Yup, that's our favourite!"
    else:
        return "Sorry, that's not our favourite IC"


if __name__ == '__main__':
    favourite_ic = 555
    print(test_ic(favourite_ic))

运行截图:

8.bytearray([source[, encoding[, errors]]]):返回一个新的 bytes 数组。 bytearray 类是一个可变序列,包含范围为 0 <= x < 256 的整数。它有可变序列大部分常见的方法,见 可变序列类型 的描述;同时有 bytes 类型的大部分方法,参见 bytes 和 bytearray 操作。

# 如果是一个整数,将会按照整数的数值,使用对应数量的空字节(\x00)来表示。比如参数为5,那么返回的结果则是b'\x00\x00\x00\x00\x00';必须为非负数,否则报错;
b=bytearray(2)
print(b)  # bytearray(b'\x00\x00')
print(len(b))  # 2

b=bytearray(0)
print(b)  # bytearray(b'')
print(len(b))  # 0

# b=bytearray(-2)  # 报错:ValueError: negative count


# 如果是一个字符串,还必须给出编码,否则会报错
# 当source参数为实现了buffer接口的object对象时,那么将使用只读方式将字节读取到字节数组后返回
b=bytearray("abc","utf-8")
print(b)  # bytearray(b'abc')
print(len(b))  # 3
# b=bytearray("abc")  # 报错:TypeError: string argument without an encoding

# 如果是一个 iterable 可迭代对象(列表(list),元组(tuple),range()方法以及for循环),它的元素的范围必须是 0 <= x < 256 的整数,它会被用作数组的初始内容
b=bytearray([1,2])
print(b)  # bytearray(b'\x01\x02')
print(len(b))  # 2

b=bytearray((1,2))
print(b)  # bytearray(b'\x01\x02')
print(len(b))  # 2

b=bytearray(set((1,2)))
print(b)  # bytearray(b'\x01\x02')
print(len(b))  # 2

b=bytearray(range(1,2))
print(b)  # bytearray(b'\x01')
print(len(b))  # 1

b=bytearray(i for i in range(1,5))
print(b)  # bytearray(b'\x01\x02\x03\x04')
print(len(b))  # 4

# 如果没有参数,则创建一个大小为0的数组。
b=bytearray()
print(b)  # bytearray(b'')
print(len(b))  # 0

以下是常见方法:

(1)clear():该方法无返回值

b=bytearray(i for i in range(1,5))
print(b.clear())  # None
print(b)  # bytearray(b'')

b=bytearray()
b.clear()
print(b)  # bytearray(b'')
print(len(b))  # 0

(2)append(x):0≤x<256,x为整数,该方法无返回值

b=bytearray(i for i in range(1,5))
print(b.append(7))  # None
print(b)  # bytearray(b'\x01\x02\x03\x04\x07')

b=bytearray()
b.append(1)
print(b)  # bytearray(b'\x01')
print(len(b))  # 1
b.append(0)
print(b)  # bytearray(b'\x01\x00')
b.append(255)
print(b)  # bytearray(b'\x01\x00\xff')

# b.append(-1)  #报错:ValueError: byte must be in range(0, 256)
# b.append((2,3))  # 报错:TypeError: an integer is required

9.bytes([source[, encoding[, errors]]]):返回一个新的 bytes 数组。 bytearray 类是一个不可变序列,包含范围为 0 <= x < 256 的整数

b=bytes(2)
print(b)  # b'\x00\x00'
print(len(b))  # 2

b=bytes("abc","utf-8")
print(b)  # b'abc'
print(len(b))  # 3

# b=bytes("abc")  # 报错:TypeError: string argument without an encoding

b=bytes("啦","utf-8")
print(b)  # b'\xe5\x95\xa6'
print(len(b))  # 3

b=bytes("你好","utf-8")
print(b)  # b'\xe4\xbd\xa0\xe5\xa5\xbd'
print(len(b))  # 6

b=bytes(2)
print(b)  # b'\x00\x00'
print(len(b))  # 2
b=bytes("abc","utf-8")
print(b)  # b'abc'
print(len(b))  # 3

b=bytes([1,2])
print(b)  # b'\x01\x02'
print(len(b))  # 2

b=bytes((1,2))
print(b)  # bb'\x01\x02'
print(len(b))  # 2

b=bytes(set((1,2)))
print(b)  # b'\x01\x02'
print(len(b))  # 2

b=bytes(range(1,2))
print(b)  # b'\x01'
print(len(b))  # 1

b=bytes()
print(b)  # b''
print(len(b))  # 0

# b=bytes(range(1,257))  #报错: ValueError: bytes must be in range(0, 256)

10.callable(obj):检测obj是否可调用

(1)对于函数、方法、lambda 函式、 类、实现了 __call__ 方法的类实例, 都是可调用

(2)对于整数,字符串,列表,元组,字典等不可调用

print(callable(0))  # False
print(callable(1))  # False
print(callable("abc"))  # False
print(callable([1,2]))  # False
print(callable((2,3)))  # False
print(callable(set([1,2])))  # False

def add(a,b):
    return a+b
print(callable(add))  # True


class A:
    """docstring for A"""
    def abc(self):
        return 0
print(callable(A))  # True

a=A()
print(callable(a))  # False


class B:
    def __call__(self):
        return 0
print(callable(B))  # True

b=B()
print(callable(b))  # True


f=lambda x: x+1
print(callable(f))  # True

11.chr(i):返回 Unicode 码位为整数 i 的字符的字符串格式

(1)实参的合法范围是 0 到 1,114,111(16 进制表示是 0x10FFFF)。如果 i 超过这个范围,会触发 ValueError 异常

print(chr(97))  # a
print(chr(90))  # Z
print(chr(0))  #
print(chr(8364))  # €
print(chr(125))  # }
print(chr(0x30))  # 0
# print(chr(12345678))  # 报错:ValueError: chr() arg not in range(0x110000)

12.@classmethod:把一个方法封装成类方法

(1)3种类定义方法:常规方法、@classmethod修饰方法、@staticmethod修饰方法

class A():
    def foo(self, x):
        print("1-executing foo(%s,%s)" % (self, x))
        print('1-self:', self)
    @classmethod
    def class_foo(cls, x):
        print("2-executing class_foo(%s,%s)" % (cls, x))
        print('2-cls:', cls)
    @staticmethod
    def static_foo(x):
        print("3-executing static_foo(%s)" % x)
a = A()

     1)普通的类方法foo()需要通过self参数隐式的传递当前类对象的实例; @classmethod修饰的方法class_foo()需要通过cls参数传递当前类对象;@staticmethod修饰的方法定义与普通函数一样。self和cls的区别不是强制的,只是PEP8中一种编程风格,self通常用作实例方法的第一参数,cls通常用作类方法的第一参数。即通常用self来传递当前类对象的实例,cls传递当前类对象

     2)foo方法绑定对象A的实例,class_foo方法绑定对象A,static_foo没有参数绑定

print(a.foo)  # <bound method A.foo of <__main__.A object at 0x0000028D5A300BA8>>
print(a.class_foo)  # <bound method A.class_foo of <class '__main__.A'>>
print(a.static_foo)  # <function A.static_foo at 0x0000028D5AAD2840>

     3)foo可通过实例a调用,类对像A直接调用会参数错误

print(a.foo(1))  # 1-executing foo(<__main__.A object at 0x0000017229EC0BA8>,1)
                 # 1-self: <__main__.A object at 0x0000017229EC0BA8>
                 # None

# print(A.foo(1))  # 报错:TypeError: foo() missing 1 required positional argument: 'x'

     4)但foo如下方式可以使用正常,显式的传递实例参数a

print(A.foo(a,1))  # 1-executing foo(<__main__.A object at 0x000002608CDD0BA8>,1)
                   # 1-self: <__main__.A object at 0x000002608CDD0BA8>
                   # None

     5)class_foo通过类对象或对象实例调用

print(A.class_foo(1))  # 2-executing class_foo(<class '__main__.A'>,1)
                       # 2-cls: <class '__main__.A'>
                       # None
print(a.class_foo(1))  # 2-executing class_foo(<class '__main__.A'>,1)
                       # 2-cls: <class '__main__.A'>
                       # None

     6)static_foo通过类对象或对象实例调用

print(A.static_foo(1))  # 3-executing static_foo(1)
                        # None
print(a.static_foo(1))  # 3-executing static_foo(1)
                        # None

     7)继承与覆盖普通类函数是一样的

class B(A):
    pass
b = B()
b.foo(1)  # 1-executing foo(<__main__.B object at 0x0000018E5FF10FD0>,1)
          # 1-self: <__main__.B object at 0x0000018E5FF10FD0>
b.class_foo(1)  # 2-executing class_foo(<class '__main__.B'>,1)
                # 2-cls: <class '__main__.B'>
b.static_foo(1)  # 3-executing static_foo(1)

     8)@staticmethod是把函数嵌入到类中的一种方式,函数就属于类,同时表明函数不需要访问这个类。通过子类的继承覆盖,能更好的组织代码

     9)区别:@staticmethod 会硬编码,就是说,方法中返回的类名必须与当前的 class 名称一致
                     @classmethod 是软编码,该方法传递的第一个参数使 cls ,cls 默认绑定了当前的类名

          具体例子可见:https://blog.csdn.net/grace666/article/details/100990469

class Fuck:
    sex = '每日' #这就是非绑定的属性
    @staticmethod
    def sta():
        return Fuck.sex
    @classmethod
    def cla(cls):
        return cls.sex  #@classmethod里面必须要传入一个参数,这个参数代表就是当前的类
class Fuck_everybody(Fuck):   #因为Fuck_everybody继承了父类Fuck,所以Fuck_everybody可以调用父类的sta()方法与cla()方法
    pass

print(Fuck_everybody.sta())  # 每日
print(Fuck_everybody.cla())  # 每日

# 然后我突然不爽,把Fuck删掉了
del Fuck
#那么,你再试试
# print(Fuck_everybody.sta())  # 报错:NameError: name 'Fuck' is not defined
print(Fuck_everybody.cla())  # 每日
#虽然删掉,但是仍能执行

https://www.zhihu.com/question/20021164?sort=created

13.compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1):

(1)source:常规的字符串、字节字符串,或者 AST (抽象语法树)对象

        filename:实参需要是代码读取的文件名;如果代码不需要从文件中读取,可以传入一些可辨识的值(经常会使用 '<string>')

        mode:指定编译代码必须用的模式。如果 source 是语句序列,可以是 'exec';如果是单一表达式,可以是 'eval';如果是单个交互式语句,可以是 'single'。(在最后一种情况下,如果表达式执行结果不是 None 将会被打印出来。)

        flags:变量作用域,局部命名空间,如果被提供,可以是任何映射对象

        flags和dont_inherit是用来控制编译源码时的标志,如果两者都未提供(或都为零)则会使用调用 compile() 的代码中有效的 future 语句来编译代码。 如果给出了 flags 参数但没有 dont_inherit (或是为零) 则 flags 参数所指定的 以及那些无论如何都有效的 future 语句会被使用。 如果 dont_inherit 为一个非零整数,则只使用 flags 参数 -- 在调用外围有效的 future 语句将被忽略

        optimize:实参指定编译器的优化级别;默认值 -1 选择与解释器的 -O 选项相同的优化级别;显式级别为 0 (没有优化;__debug__ 为真)、1 (断言被删除, __debug__ 为假)或 2 (文档字符串也被删除)

如果编译的源码不合法,此函数会触发 SyntaxError 异常;如果源码包含 null 字节,则会触发 ValueError 异常

14.complex([real[, imag]])      复数

real---int、float、long、字符串

imag---int、float、long

当real为int、float、long时,imag可缺省或同样为int、float、long

当real为字符串时,则imag必须为能表示复数的字符串形式,如“1+2j”、“1-3j”,但是中间的“+”或“-”号两边不能有空格,并且imag必须缺省

当real和imag都缺省,返回0j

print(complex())  # 0j
print(complex(1, 2))  # (1+2j)
print(complex(3))  # (3+0j)
print(complex("4"))  # (4+0j)
print(complex(5 + 3j))  # (5+3j)
print(complex("6+5j"))  # (6+5j)
print(complex("6-5j"))  # (6-5j)
print(complex("6.1+5.2j"))  # (6.1+5.2j)
print(complex("6.1"))  # (6.1+0j)

print(complex("1+2j")) # (1+2j)
print(complex(" 1+2j")) # (1+2j)
print(complex(" 1+2j ")) # (1+2j)
# print(complex("1 +2j"))  # 报错:ValueError: complex() arg is a malformed string

可以使用下划线将代码文字中的数字进行分组:

print(complex("2_3"))  # (23+0j)
print(complex("1_1"))  # (11+0j)
print(complex("0_10"))  # (10+0j)
print(complex("1_0"))  # (10+0j)
print(complex("0_0"))  # 0j
print(complex("1_2_3"))  # (123+0j)
print(complex("1_2_3_4"))  # (1234+0j)
print(complex("1_2+3j"))  # (12+3j)
print(complex("0_2+3j"))  # (2+3j)

15.dir():

(1)如果没有实参,则返回当前本地作用域中的名称列表

print(dir())  # ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'ctime', 'datetime', 'pymongo', 'reduce']

(2)如果有实参,它会尝试返回该对象的有效属性列表

print(dir([]))  # ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

def x():
    return 1
print(dir(x))  # ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

class A():
    pass
print(dir(A))  # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
s=A()
print(dir(s))  # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值