新手请问Python函数参数值传递问题,python函数,现在有两个问题:1.如果
新手请问Python函数参数值传递问题,python函数,现在有两个问题:1.如果
现在有两个问题:
1.如果在一个类的定义中,想定义一个该类的对象,该怎么办?
class UserInfo:
bidderID = 0 #用户ID name = " " #用户名 addr = " " #IP地址 port = 0 #端口号 rname = '' #所在竞拍室名称 bidprice = 0 #出价 str='' next = UserInfo() #???
会在next= UserInfo()这里报错,提示说UserInfo未定义
2.怎样让传递给函数的参数(是一种自定义的类),在经过函数处理之后,可以改变它的值。
例如:
添加新用户n的信息
def addUser(self,n): self.pointer = self.root n.next = self.pointer.next self.pointer.next = n self.count += 1
当其他函数调用这个函数,self.userList.addUser(self.user)之后,userlist会真的增加一项。
1. 引用自身
虽然Python是动态解释型语言,但在解释到
class UserInfo: # ... next = UserInfo() # <===
这句时,由于类UserInfo还没定义结束,直接开始使用是不行的。但是Python本身由于是动态解释运行的,完全可以利用动态修改内容(甚至新增属性)来解决这个需求。例如
class UserInfo: # ... next = Noneuser = UserInfo()user.next = UserInfo()
当然,这样就做不到一个类内初始化了,那么可以使用一些魔术方法
class UserInfo: def __init__(self): # 要注意执行__new__创建的实例是没经过__init__初始化的,切记 # 这在做很多lazy-loading的时候很管用 self.next = UserInfo.__new__(UserInfo)
参考:http://www.rafekettler.com/magicmethods.html#construction
2. 参数的引用传递
简单来说
举点例子
list是可变的,如果在函数内直接对其进行修改,而不修改引用,那么将会改变参数内容
def test(n): n.append(2)m = [1]test(m)print(m) # 这里将会输出 [1, 2]
如果调换参数的引用的话
def test(n) n = [2] # 这里其实已经将参数的引用调换了m = [1]test(m)print(m) # 所以这里将输出[1]
str是不可变的,也没有对其inplace操作的方法,皆为返回一个新的copy
def test(n) n = "Hello, Python!"m = "Hello, World!"test(m)print(m) # 这里还是Hello, World!
stackoverflow上个更清楚的回答:
Python自己的文档也有说明:https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference
编橙之家文章,
相关内容
- 如何用python实现openSSL的PHP代码?,pythonopenssl,function ge
- 我的网站爬虫python代码为什么不能正常运行,哪里写错了
- Python2.7 GBK阿拉伯文字转换问题,,简单说,想问如何把
- Py模块rrdtool导入问题时报undefined symbol: rrd_flushcached?,
- python mysql Commands out of sync相关的问题,pythoncommands,py
- Python能做C/S.exe计算器程序吗?,pythons.exe,大家好,我是
- python3编辑器sublime text 2输出中文字符UnicodeEncodeError,
- Python pylo文件发送怎么操作,pythonpylo文件发送,我在用
- python文档中源码看不懂求大神指导,python大神,在查看文
- Python MongoDB正则与模糊查询出错,pythonmongodb,使用正则表
评论关闭