python如何查看类的函数?( 三 )


|
|__sizeof__($self, /)
|Return the size of the object in bytes.
|
|__subclasshook__($self, /, subclass)
|Abstract classes can override this to customize issubclass().
|
|----------------------------------------------------------------------
|Data descriptors inherited from object:
|
|__class__
|type(object_or_name) -> the object's type
|
|__delattr__
|x.__delattr__('name') <==> del x.name
|
|__dict__
|dictionary for instance variables (if defined)
|
|__dir__
|Default dir() implementation.
|
|__doc__
|str(object='') -> str
|str(bytes_or_buffer[, encoding[, errors]]) -> str
|
|Create a new string object from the given object. If encoding or
|errors is specified, then the object must expose a data buffer
|that will be decoded using the given encoding and error handler.
|Otherwise, returns the result of object.__str__() (if defined)
|or repr(object).
|encoding defaults to sys.getdefaultencoding().
|errors defaults to 'strict'.
|
|__eq__
|Return self==value.
|
|__format__
|Default object formatter.
|
|__ge__
|Return self>=value.
|
|__getattribute__
|Return getattr(self, name).
|
|__gt__
|Return self>value.
|
|__hash__
|Return hash(self).
|
|__init_subclass__
|This method is called when a class is subclassed.
|
|__le__
|Return self<=value.
|
|__lt__
|Return self |
|__ne__
|Return self!=value.
|
|__new__
|Create and return a new object.See help(type) for accurate signature.
|
|__reduce__
|Helper for pickle.
|
|__reduce_ex__
|Helper for pickle.
|
|__repr__
|Return repr(self).
|
|__setattr__
|Implement setattr(self, name, value).
|
|__sizeof__
|__sizeof__() -> int
|size of object in memory, in bytes
|
|__str__
|Return str(self).
|
|__subclasshook__
|Abstract classes can override this to customize issubclass().
```
从输出结果可以看出,help函数不仅可以查看类的方法,还可以查看类的属性和继承关系等信息 。
二、使用dir函数
dir函数可以列出一个对象的所有属性和方法 。对于类来说,dir函数可以列出该类及其基类的所有属性和方法 。代码如下:
```python
class MyClass:
def func1(self):
"""
This is func1
"""
pass
def func2(self):
"""
This is func2
"""
pass
print(dir(MyClass))
```
运行上述代码后,我们可以看到如下输出:
```
['__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__', 'func1', 'func2']
```
从输出结果可以看出,dir函数返回一个列表,其中包含类的所有方法和属性 。
三、使用inspect模块
Python的inspect模块可以帮助我们获取类的方法和属性的更多信息,例如方法的参数和返回值等 。代码如下:
```python
import inspect
class MyClass:
def func1(self, x: int, y: int) -> int:
"""
This is func1
"""
return x + y
def func2(self):
"""
This is func2
"""
pass
print(inspect.signature(MyClass.func1))
```
运行上述代码后,我们可以看到如下输出:

猜你喜欢