3 回答

TA贡献1842条经验 获得超12个赞
这
__main__
是什么意思?
直接调用的脚本被视为__main__
模块。可以与其他任何模块相同的方式导入和访问它。
自我参数传递了什么?
中包含的参考MyObject
。

TA贡献1875条经验 获得超5个赞
__main__
如果直接从命令行运行,则为当前模块的名称。如果要从另一个模块导入该模块import my_module
,则将以该名称命名。因此,印刷品会说:
< my_module.MyClass object at 0x0000000002B70E10 >

TA贡献1816条经验 获得超6个赞
第一的:
__main__表示运行该方法的类是正在运行的主文件-单击或键入到终端的文件是该类主持的文件。这就是为什么写是一个好习惯
if __name__ == "__main__":
#do stuff
在您的测试代码上-这样可以保证您的测试代码仅在从最初调用的文件运行代码时才运行。这也是为什么您永远不要编写顶级代码的原因,尤其是如果您以后想要多线程的话!
自我是识别班级的关键词。每个方法都需要有第一个参数“ self”-注意,如果没有,则不会引发错误,您的代码只会失败。调用self.variable表示查找类变量,而不是局部变量(仅在该方法内)或全局变量(每个人都可以使用)。同样,调用self.methodName()会调用属于该类的方法。
所以:
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
添加回答
举报