3 回答

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超13個(gè)贊
這
__main__
是什么意思?
直接調(diào)用的腳本被視為__main__
模塊??梢耘c其他任何模塊相同的方式導(dǎo)入和訪問(wèn)它。
自我參數(shù)傳遞了什么?
中包含的參考MyObject
。

TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超5個(gè)贊
__main__
如果直接從命令行運(yùn)行,則為當(dāng)前模塊的名稱。如果要從另一個(gè)模塊導(dǎo)入該模塊import my_module
,則將以該名稱命名。因此,印刷品會(huì)說(shuō):
< my_module.MyClass object at 0x0000000002B70E10 >

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
第一的:
__main__表示運(yùn)行該方法的類是正在運(yùn)行的主文件-單擊或鍵入到終端的文件是該類主持的文件。這就是為什么寫是一個(gè)好習(xí)慣
if __name__ == "__main__":
#do stuff
在您的測(cè)試代碼上-這樣可以保證您的測(cè)試代碼僅在從最初調(diào)用的文件運(yùn)行代碼時(shí)才運(yùn)行。這也是為什么您永遠(yuǎn)不要編寫頂級(jí)代碼的原因,尤其是如果您以后想要多線程的話!
自我是識(shí)別班級(jí)的關(guān)鍵詞。每個(gè)方法都需要有第一個(gè)參數(shù)“ self”-注意,如果沒有,則不會(huì)引發(fā)錯(cuò)誤,您的代碼只會(huì)失敗。調(diào)用self.variable表示查找類變量,而不是局部變量(僅在該方法內(nèi))或全局變量(每個(gè)人都可以使用)。同樣,調(diào)用self.methodName()會(huì)調(diào)用屬于該類的方法。
所以:
class Foo: #a new class, foo
def __init__( self ):
#set an object variable to be accessed anywhere in this object
self.myVariable = 'happy'
#this one's a local variable, it will dissapear at the end of the method's execution
myVaraible = sad
#this calls the newMethod method of the class, defined below. Note that we do NOT write self when calling.
self.newMethod( "this is my variable!" )
def newMethod (self, myVariable):
#prints the variable you passed in as a parameter
print myVariable
#prints 'happy', because that's what the object variable is, as defined above
print self.myVariable
添加回答
舉報(bào)