callable() 是可调用对象?
内置函数 callable(),Python 官方文档描述如下:
help(callable)
Help on built-in function callable in module builtins:
callable(obj, /)
Return whether the object is callable (i.e., some kind of function).
Note that classes are callable, as are instances of classes with a
__call__() method.
如果 obj 是可调用对象就返回 True,否则返回 False。如果返回 True,调用仍可能失败,但如果返回 False,则调用将肯定不会成功。
函数、方法、类以及实现了 __call__()
方法的类的实例是可调用的。
callable(1)
False
callable(int)
True
class Myint(int):
def __call__(self):
pass
num = Myint(1)
num
1
callable(num)
True
callable(lambda: 1)
True
chr() 返回 Unicode 码位值对应字符
内置函数 chr(),Python 官方文档描述如下:
help(chr)
Help on built-in function chr in module builtins:
chr(i, /)
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
返回 Unicode 码位对应的字符的字符串格式。码位范围是 0~1114111(16 进制表示是 0x10FFFF),超过这个范围,会触发 ValueError 异常。该函数是 ord() 的逆函数。
chr(97)
'a'
ord('a')
97
chr(1114111)
'\U0010ffff'
chr(1114112)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-5-4857faf08086> in <module>
----> 1 chr(1114112)
ValueError: chr() arg not in range(0x110000)
classmethod 封装函数为类方法
内置函数(类)classmethod,Python 官方文档描述如下:
help(classmethod)
Help on class classmethod in module builtins:
class classmethod(object)
| classmethod(function) -> method
|
| Convert a function to be a class method.
|
| A class method receives the class as implicit first argument,
| just like an instance method receives the instance.
| To declare a class method, use this idiom:
|
| class C:
| @classmethod
| def f(cls, arg1, arg2, ...):
| ...
|
| It can be called either on the class (e.g. C.f()) or on an instance
| (e.g. C().f()). The instance is ignored except for its class.
| If a class method is called for a derived class, the derived class
| object is passed as the implied first argument.
|
| Class methods are different than C++ or Java static methods.
| If you want those, see the staticmethod builtin.
|
| Methods defined here:
|
| __get__(self, instance, owner, /)
| Return an attribute of instance, which is of type owner.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
|
| __func__
|
| __isabstractmethod__
把一个函数封装成类方法。一个类方法把类自己作为第一个实参,就像一个实例方法把实例自己作为第一个实参。
可将函数作为参数来声明类方法,但请用习惯的装饰器形式(@classmethod)来声明类方法。
type(classmethod)
type
class A<