在Python脚本中使用self和参数

在Python脚本中使用self和参数,python,python-3.x,Python,Python 3.x,我希望在Python脚本中使用self(用于全局变量)和命令行中的参数,但实际上无法让它们工作 def otherFunction(self) print self.tecE def main(argv,self): self.tecE = 'test' otherFunction() if __name__ == "__main__": main(sys.argv[1:],self) 这给了我一个错误: main(sys.argv[1:],self)

我希望在Python脚本中使用self(用于全局变量)和命令行中的参数,但实际上无法让它们工作

def otherFunction(self)
    print self.tecE

def main(argv,self):
    self.tecE = 'test'
    otherFunction()

if __name__ == "__main__":
   main(sys.argv[1:],self)
这给了我一个错误:

    main(sys.argv[1:],self)
NameError: name 'self' is not defined

那么如何以及在何处定义
self

通常在python类中使用
self
的python约定,您做得有点乱

因此,要么你不使用类,把自我当作一个整体,就像这样:

import sys
myglobal = {} # Didn't want to name it self, for avoiding confusing you :)

def otherFunction():
    print myglobal["tecE"]

def main(argv):
    myglobal["tecE"] = 'test'
    otherFunction()

if __name__ == "__main__":
   main(sys.argv[1:])
import sys

class MyClass():

    def otherFunction(self):
        print self.tecE

    def main(self, argv):
        self.tecE = 'test'
        self.otherFunction() # Calling other class members (using the self object which actually acting like the "this" keyword in other languages like in Java and similars)

if __name__ == "__main__":
   myObj = MyClass()  # Instantiating an object out of your class
   myObj.main(sys.argv[1:])
或者写一个类,像这样:

import sys
myglobal = {} # Didn't want to name it self, for avoiding confusing you :)

def otherFunction():
    print myglobal["tecE"]

def main(argv):
    myglobal["tecE"] = 'test'
    otherFunction()

if __name__ == "__main__":
   main(sys.argv[1:])
import sys

class MyClass():

    def otherFunction(self):
        print self.tecE

    def main(self, argv):
        self.tecE = 'test'
        self.otherFunction() # Calling other class members (using the self object which actually acting like the "this" keyword in other languages like in Java and similars)

if __name__ == "__main__":
   myObj = MyClass()  # Instantiating an object out of your class
   myObj.main(sys.argv[1:])
那么如何以及在哪里定义自我呢

您将使用self:

  • 作为类方法的第一个参数
    def my_方法(self,arg1,arg2):
  • 在类内引用任何其他类成员(如上所示)
    self.do\u job(“something”,123)
  • 用于创建类成员:
    self.new\u field=56
    通常在
    \uuuu init\uuuu()构造函数方法中

  • 注意:不带
    self.new\u var
    标记类变量将创建一个静态类变量。

    main中的
    self
    是什么?
    self
    通常仅与类结合使用。。。我假设您从其他地方(使用了class关键字的地方)复制粘贴了此代码(主要是不同的函数),但没有理解它。我希望以使用此
    的方式使用它。我不介意用它来创建一个类,但是对于要在命令行中运行的简单脚本,是否有某种使用全局变量和参数的模板?对于
    this
    self
    ,它们只是变量名。不管是在课堂内还是课堂外。你必须像其他变量一样定义它们。在类中使用
    self
    来引用当前类实例只是一种惯例。你对
    这个
    是什么意思<代码>这是Java,不是Python。python类语法与第一个示例中的java语法有点不同,您可以简单地使用关键字global而不是使用字典。我认为您不应该鼓励OP在类之外使用
    self
    。他们已经认为这意味着一些它没有的东西(尽管不清楚是什么)。使用不同的名称。