首页 文章

什么是variable.methodName()函数/方法调用?

提问于
浏览
-1

超级简单的问题:这些类型的方法/函数叫什么?

"Some random string".upper()
"A string in python".lower()
"A formatted string {}".format("in Python")

我真的很想找到我能做的一切以及如何制作它们,但据我所知,它们被称为“阶级方法”,它与天空一样广泛 . 我问我的CS老师,但即使他没有真正的答案 .

2 回答

  • 0

    他们都是 builtin_function_or_method

    >>> type('ABC'.lower)
    <class 'builtin_function_or_method'>
    >>>
    

    但是更像是字符串方法

    这些是 method_descriptor

    >>> type(str.lower)
    <class 'method_descriptor'>
    >>>
    

    使用 type 来做这些事情 .

  • 0

    这些被称为实例方法,因为它们在类的实例上操作,在这种情况下 "Some random string"str 类的实例, upper() 方法直接在该实例本身上操作 .

    区分它们的一个好方法是问问自己,该方法是否需要有关特定实例的信息?例如, upper() 是否需要知道特定字符串实例中的文本才能完成其工作?

    相比之下,类方法不对类的特定实例进行操作 . 例如,https://docs.python.org/3.7/library/stdtypes.html#int.from_bytes

    返回给定字节数组表示的整数 . >>> int.from_bytes(b'\ x00 \ x10',byteorder ='big')
    16

    int.from_bytes(b'\ x00 \ x10',byteorder ='little')
    4096
    int.from_bytes(b'\ xfc \ x00',byteorder ='big',signed = True)
    -1024
    int.from_bytes(b'\ xfc \ x00',byteorder ='big',signed = False)
    64512
    int.from_bytes([255,0,0],byteorder ='big')
    16711680

    在这种情况下,方法 from_bytes 不需要有关int类的任何特定实例的信息,因为它是构造实例的实例 .

相关问题