Python常看函数用法,返回值类型

Python的函数非常多,可以使用help()函数来初略的获得函数的用法

help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

同时我们自己定义函数时,也可以适当的来解释这个函数的作用

def times(s:str,n:int) ->str:  # 返回值为str类型
    '''
    返回n个s字符串
    '''
    return s*n
print(times('北山啦',3))
北山啦北山啦北山啦

同时,可以使用.__annotations__方法获取函数的类型注释

times.__annotations__
{'s': str, 'n': int, 'return': str}

他就以字典的形式返回了他的两个参数,以及一个str类型的返回值

查看函数文档使用.__doc__方法

print(times.__doc__)
    返回n个s字符串

在面向对象编程中,python 类有多继承特性,如果继承关系太复杂,很难看出会先调用那个属性或方法。

为了方便且快速地看清继承关系和顺序,可以使用.__mro__

class X(object):pass
class Y(object):pass
class A(X, Y):pass
class B(Y):pass
class C(A, B):pass
 
print C.__mro__
# (<class '__main__.C'>, <class '__main__.A'>,
#  <class '__main__.X'>, <class '__main__.B'>, 
# <class '__main__.Y'>, <type 'object'>)

猜你喜欢

转载自blog.csdn.net/qq_45176548/article/details/124911348