我越来越深入地了解 python,发现很难理解接口的概念。
\n\n这个问题更具理论性。
\n\n据我了解,为最终用户(非开发人员用户)提供一个接口是可取的,但是为什么类也应该具有供其他对象/类(基本上是其他程序/程序员)使用的接口?\n在示例中,在 B 类中使用 comment1 或 comment 2 如何改变程序的功能?
\n\nclass A():\n def __init__(self,a):\n self.a = a\n print self.a\n def seta(self,newa): #setter\n self.a = newa\n print self.a\n def geta(self): #getter\n return self.a\n\n\nclass B(object):\n def __init__(self,oobj,b):\n self.b = b\n self.oobj = oobj\n print self.b\n def addab(self):\n #a = self.oobj.geta() # \xe2\x80\x94> 1. using interface : the getter method \n #return (self.b +a)\n return (self.b+self.oobj.a) # \xe2\x80\x94> 2.directly accessing the a attribute\n
Run Code Online (Sandbox Code Playgroud)\n\n希望我已经说清楚了..
\n\n编辑:\n我确实检查了提到的可能重复的其他线程,但即使在尝试理解@property之前,我也试图理解不通过程序内的不同对象自行修改属性背后的基本原理。
\n可以理解的是,为合并排序算法和计数反转创建了多个线程.虽然这是课程课程的家庭作业问题,但我很难理解在计算反演次数时我的实施方法出错了.与参加该课程的其他人相比,对于少数测试示例,我似乎得到了非常不切实际的低值.以下是我的代码:
count = 0
def sort_list(unsortedlist):
m = len(unsortedlist)
A_list = unsortedlist[:m/2]
B_list = unsortedlist[m/2:]
if len(A_list) > 1: # if the list is longer thn 2 items, break it up
A_list = sort_list(A_list)
if len(B_list) > 1: # breaking and sorting second part
B_list = sort_list(B_list)
return merge_sort(A_list,B_list) # merge the smaller lists to return either a-list/b_list or full_list
def merge_sort(a_list,b_list):
initiallist = a_list+b_list
final_list = []
i = 0
j = 0
global count
while len(final_list) < (len(initiallist)): …
Run Code Online (Sandbox Code Playgroud) 我编写了一段代码,其中列表大小随着每次迭代而增加,迭代次数可以达到近100000次.
样品:
def do_something():
Lst.append(k)
while N < 100000:
if k not in Lst:
do_something()
Run Code Online (Sandbox Code Playgroud)
现在,我注意到这种方法需要很长时间才能完成.请注意,我确实设置了setrecursionlimit().事实上令人尴尬的是,该计划一直在运行.
之后,在尝试寻找优化代码的方法时,我将Lst转换为Dct.所以代码看起来像:
def do_something():
Dct[k] = True
while N < 100000:
if Dct[k] == False:
do_something()
Run Code Online (Sandbox Code Playgroud)
代码运行得更快.在阅读了几个关于SOF的对话(重复附加到大型列表(Python 2.6.6))后,我意识到它的列表不是很慢,而是如何处理更大的列表数据的内存.这个网站https://wiki.python.org/moin/TimeComplexity,揭示了列表和dict查找时间的复杂性.列表中的O(n),其中Dct查找为O(1).这是Dct表现更好的原因吗?如何执行列表查找和Dict查找?