[英]Python function arguments and documentation confusion
Here is a string in python: 这是python中的字符串:
a = "asdf as df adsf as df asdf asd f"
Lets say that I want to replace all " " with "||", so I do: 可以说我想用“ ||”替换所有的“”,所以我这样做:
>>> a.replace(" ", "||")
'asdf||as||df||adsf||as||df||asdf||asd||f'
My confusion is info from the documentation as below: 我的困惑是来自文档的信息,如下所示:
string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences...
I can "omit" s
, but based on the documentation I need s
; 我可以“省略”
s
,但是基于我需要的文档上s
; however, I only provide old
, and new
. 但是,我只提供
old
和new
。 I noticed that it's like this with a lot of the python documentation; 我注意到很多python文档都是这样。 what am I missing?
我想念什么?
You are mixing up str
object methods with the string
module functions. 您正在将
str
对象方法与string
模块函数混合在一起。
The documentation you are referring to is the string
module documentation. 您要参考的文档是
string
模块文档。 Indeed, there is a function in the string module called replace
which takes 3 (or optionally, 4) arguments: 实际上,字符串模块中有一个函数称为
replace
,该函数接受3个(或可选的4个)参数:
In [9]: string
Out[9]: <module 'string' from '/usr/lib/python2.7/string.pyc'>
In [11]: string.replace(a, ' ', '||')
Out[11]: 'asdf||as||df||adsf||as||df||asdf||asd||f'
a
is a str
object -- ( str
is a type, string
is a module): a
是一个str
对象-( str
是一个类型, string
是一个模块):
In [15]: type(a)
Out[15]: str
And str
objects have a replace
method. 并且
str
对象具有replace
方法。 The documentation for the str
methods is here . str
方法的文档在这里 。
When you call a method of an object, the object is supplied automatically as the first parameter. 调用对象的方法时,将自动提供该对象作为第一个参数。 Generally within the method this is referred to as
self
. 通常在方法中将其称为
self
。
So you can call the function passing in the object: 因此,您可以调用传入对象的函数:
string.replace(s, old, new)
or you can call the method of the object: 或者您可以调用对象的方法:
s.replace(old, new)
Both are functionally identical. 两者在功能上是相同的。
The first parameter of a method is a reference to the object (usually called self
) being modified and is implicitly passed when you use the object.method(...)
notation. 方法的第一个参数是对要修改的对象(通常称为
self
)的引用,并在使用object.method(...)
表示法时隐式传递 。 So this: 所以这:
a = "asdf as df adsf as df asdf asd f"
print a.replace(" ", "||")
is equivalent to this: 等效于此:
a = "asdf as df adsf as df asdf asd f"
print str.replace(a, " ", "||")
str
being the class of the a
object. str
是a
对象的类。 It's just syntactical sugar. 这只是语法糖。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.