Setting/Resetting 在 __init__ 中声明和初始化的变量的值在 __main__ 中

Setting/Resetting the value of a variable that is declared and initialized in __init__ in __main__

我想设置/重置我在 main 中的 init 中初始化的变量值。我有以下代码。

class myClass:

    def myfun(self):

       # code using the url

    def __init__(self):
        self.url = None

if __name__ == '__main__':

   # list of integers
   my_list = [1, 2, 3,4,5]
   count = 0

   for item in my_list:
       if count % 2 == 0:
           self.url = "http://myurl.com" # I want to set/reset my url here

我收到此错误:

NameError: name 'self' is not defined`

我可以对 set/reset 我的变量做些什么,以后可以在我的 class 的所有方法中全局使用?

import guard if __name__ == '__main__': 及其中的所有内容都在全局命名空间中。它不是您 class 的一部分,更不是 class 中的方法。要拥有 class 的实例,您需要实例化它:

my_obj = myClass()

现在,在同一个命名空间中,您可以

my_obj.url = ...

接着是

my_obj.myfun()

您需要实例化您的 class,并使用此名称来引用您的 class,而不是 self。像这样:

class myClass:

    def myfun(self):
        pass
       # code using the url

    def __init__(self):
        self.url = None

if __name__ == '__main__':

   # list of integers
   my_list = [1, 2, 3,4,5]
   count = 0
   obj = myClass() # HERE!
   for item in my_list:
       if count % 2 == 0:
           obj.url = "http://myurl.com"

您需要在实例化后将 class 称为 obj(或您为其指定的任何其他名称)。如果您不实例化 class,它只是某种具有预定义属性和行为的骨架,但目前还不存在。你不能在实例化之前操作它。

实例化后,你可以用实例名来引用它,在我的例子中是objself 在 class 中指的是它自己,无论它在实例化时被称为什么。所以在 class 之外,你不能使用 self.

我想你想要一个 class 变量。

that can be used globally later on in all the methods of my class

当你使用self.url时,如果实例中没有url属性,它会引用class变量。它由所有实例共享。如果您在某些实例上定义 self.url,它们的 self.url 将被隐藏。

class MyClass:
    url = None

    def my_fun(self):
        print(self.url)
        # code using the url


if __name__ == '__main__':

    # list of integers
    my_list = [1, 2, 3, 4, 5]
    count = 0
    my_object = MyClass()

    for item in my_list:
        if count % 2 == 0:
            MyClass.url = "http://myurl.com"  # I want to set/reset my url here
            my_object.my_fun()

问题是 self 表示从 class 创建的对象,并且在 if main 语句中不可访问。

self 只能在 class 方法中使用。

您需要实例化 myClass 然后调用 myClass.url

例如:

class MyClass:

def myfun(self):

   # code using the url

def __init__(self):
    self.url = None

if __name__ == '__main__':

   # list of integers
   my_list = [1, 2, 3,4,5]
   count = 0
   my_class = MyClass()


   for item in my_list:
       if count % 2 == 0:
           my_class.url = "http://myurl.com" # I want to set/reset my url here

我还冒昧地将您的 class 重命名为 MyClass,因为这更像 pythonic