Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

inspection - What is the meaning of a forward slash "/" in a Python method signature, as shown by help(foo)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As explained here, the '/' as an argument marks the end of arguments that are positional only (see here), i.e. arguments you can't use as keyword parameters. In the case of __eq__(self, value, /) the slash is at the end, which means that all arguments are marked as positional only while in the case of your __init__ only self, i.e. nothing, is positional only.

Edit: This was previously only used for built-in functions but since Python 3.8, you can use this in your own functions. The natural companion of / is * which allows to mark the beginning of keyword-only arguments. Example using both:?

# a, b are positional-only. e,f keyword-only
def f(a, b, /, c, d, *, e, f):
    print(a, b, c, d, e, f)

# valid call
f(10, 20, 30, d=40, e=50, f=60)

# invalid calls:
f(10, b=20, c=30, d=40, e=50, f=60)   # b cannot be a keyword argument
f(10, 20, 30, 40, 50, f=60)           # e must be a keyword argument

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...