python课堂上太多自我 [英] python too many self in class
本文介绍了python课堂上太多自我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习Python OOP,并试图将Java类转换为Python类
I'm learning Python OOP and trying to convert a Java class to a Python class
有关Java代码,请参见此PDF文档的第15页google doc 链接
See page 15 in this PDF for Java code google doc link
class QuickFindUF:
"""docstring for QuickFindUF"""
def __init__(self, n):
self.id = []
for e in range(n):
self.id.append(e)
def connected(self,p,q):
return self.id[p]==self.id[q]
def union(self,p,q):
self.pid = self.id[p]
self.qid = self.id[q]
for i in range(len(self.id)):
if(self.id[i]==self.pid):
self.id[i]=self.qid
quf = QuickFindUF(9)
quf.union(3,4)
print quf.connected(3,4)
此类中有16个 self
关键字.有没有更好的方法编写此类?
There are 16 self
keywords in this class. Is there a better way to write this class?
推荐答案
是的,您不想将这些变量分配给 self
,这些是局部变量:
Yea, you don't want to assign these variables to self
, these are local variables:
def union(self,p,q):
self.pid = self.id[p]
self.qid = self.id[q]
for i in range(len(self.id)):
if(self.id[i]==self.pid):
self.id[i]=self.qid
应该是:
def union(self,p,q):
pid = self.id[p]
qid = self.id[q]
for i in range(len(self.id)):
if self.id[i] == pid:
self.id[i] = qid
仅在引用实例变量时使用 self
,而不是方法内部的任何变量.
You only use self
when referring to instance variables, not to any variable inside of a method.
这篇关于python课堂上太多自我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文