这个问题在这里已经有了答案:Whatisthepurposeofthe`self`parameter?Whyisitneeded?(26个回答)关闭2个月前。在Python中(在同一模块内)引用成员函数时是否应该使用self?更一般地说,我想知道何时需要使用self,不仅用于方法,还用于变量。 最佳答案 添加答案,因为Oskarbi的答案不明确。您在以下情况下使用self:定义实例方法。当您在实例上调用方法时,它会自Action为第一个参数传递,并且它是调用该方法的实例。从实例方法内部引用类或实例属性。当您想从该方法内部调用方法或访
这个问题在这里已经有了答案:nonlocalkeywordinPython2.x(10个回答)Isitpossibletomodifyavariableinpythonthatisinanouter(enclosing),butnotglobal,scope?(9个回答)关闭8年前。对于以下Python2.7代码:#!/usr/bin/pythondeffunc_a():print"func_a"c=0deffunc_b():c+=3print"func_b",cdeffunc_c():print"func_c",cprint"c",cfunc_b()c+=2func_c()c+=2f
这个问题在这里已经有了答案:nonlocalkeywordinPython2.x(10个回答)Isitpossibletomodifyavariableinpythonthatisinanouter(enclosing),butnotglobal,scope?(9个回答)关闭8年前。对于以下Python2.7代码:#!/usr/bin/pythondeffunc_a():print"func_a"c=0deffunc_b():c+=3print"func_b",cdeffunc_c():print"func_c",cprint"c",cfunc_b()c+=2func_c()c+=2f
我有一个类A,它被一堆其他类继承。其中一些具有一些相似的函数,最好将这些函数定义在其他地方并由需要它们的类调用。但是这些函数调用父类(superclass)中定义的函数。classA():defimp_func(*args):#calledbythechildclassfunctionsClassB(A):defcommon_func(self):#somestuffself.imp_func(*args)所以我创建了我的辅助函数,它以self对象作为参数,我可以从辅助函数内部调用imp_func。defhelper_func(obj,some_args):#somecommonstu
我有一个类A,它被一堆其他类继承。其中一些具有一些相似的函数,最好将这些函数定义在其他地方并由需要它们的类调用。但是这些函数调用父类(superclass)中定义的函数。classA():defimp_func(*args):#calledbythechildclassfunctionsClassB(A):defcommon_func(self):#somestuffself.imp_func(*args)所以我创建了我的辅助函数,它以self对象作为参数,我可以从辅助函数内部调用imp_func。defhelper_func(obj,some_args):#somecommonstu
我也尝试过寻找答案,但我不明白其他人类似问题的答案...tfile=open("/home/path/to/file",'r')deftemp_sky(lreq,breq):forlineintfile:data=line.split()if(abs(float(data[0])-lreq)我收到以下错误7.37052488Traceback(mostrecentcalllast):File"tsky.py",line25,inprinttemp_sky(10,-10)File"tsky.py",line22,intemp_skyreturnTUnboundLocalError:loc
我也尝试过寻找答案,但我不明白其他人类似问题的答案...tfile=open("/home/path/to/file",'r')deftemp_sky(lreq,breq):forlineintfile:data=line.split()if(abs(float(data[0])-lreq)我收到以下错误7.37052488Traceback(mostrecentcalllast):File"tsky.py",line25,inprinttemp_sky(10,-10)File"tsky.py",line22,intemp_skyreturnTUnboundLocalError:loc
这个问题在这里已经有了答案:Whatisthepurposeofthe`self`parameter?Whyisitneeded?(26个回答)关闭6年前。我对OOP术语和概念几乎一无所知。我从概念上知道对象是什么,并且对象具有方法。我什至明白在python中,类是对象!不错,就是不知道什么意思它没有点击我。我目前正在尝试了解一些我认为可以阐明我对python的理解的详细答案:Whatdoesthe"yield"keyworddoinPython?WhatisametaclassinPython?在第一个答案中,作者以如下代码为例:>>>classBank():#let'screate
这个问题在这里已经有了答案:Whatisthepurposeofthe`self`parameter?Whyisitneeded?(26个回答)关闭6年前。我对OOP术语和概念几乎一无所知。我从概念上知道对象是什么,并且对象具有方法。我什至明白在python中,类是对象!不错,就是不知道什么意思它没有点击我。我目前正在尝试了解一些我认为可以阐明我对python的理解的详细答案:Whatdoesthe"yield"keyworddoinPython?WhatisametaclassinPython?在第一个答案中,作者以如下代码为例:>>>classBank():#let'screate
我对python还很陌生,并注意到这些帖子:Python__init__andselfwhatdotheydo?和PythonClasseswithoutusingdef__init__(self)然而,在玩弄它之后,我注意到这两个类给出了明显相同的结果-classA(object):def__init__(self):self.x='Hello'defmethod_a(self,foo):printself.x+''+foo(来自thisquestion)和classB(object):x='Hello'defmethod_b(self,foo):printself.x+''+foo