|
发表于 2021-3-25 16:42:06
|
显示全部楼层
- class A():
- pass
- a = A()
- help(a.__init__())
复制代码
运行上述代码得到:
Help on NoneType object:
class NoneType(object)
| Methods defined here:
|
| __bool__(self, /)
| self != 0
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
如果还不清楚,运行下面代码
- class A(object):
- def __init__(self): # 无需返回值,参数是__new__返回的实例
- print('这是init方法-->', self)
- def __new__(cls):
- '''有返回值,参数是cls则表示是当前类实例
- 如果是其他类的类名,那么实际创建返回的就是其他类的实例
- 就不会调用当前类的__init__函数,也不会调用其他类的__init__函数'''
- print('这是cls的ID-->', id(cls))
- print('这是new方法-->', object.__new__(cls))
- return object.__new__(cls)
- A()
- print('这是类A的ID-->', id(A))
复制代码 |
|