python类中的全局变量分配

时间:2020-02-08 11:15:53

标签: python oop beautifulsoup

我的XmlParser接收文件名,然后按文件名读取,然后为不同的方法创建汤。我试图使汤全局变量。但是我指的是构造函数变量,并且我响应:'NameError:未定义名称'self''

from bs4 import BeautifulSoup
from tools import read_file


class XmlParser:
    soup = BeautifulSoup(self.xml_file, self.parser_type)

    def __init__(self, file_name, parser_type):
        self.xml_file = read_file(file_name)
        self.parser_type = parser_type

如何在构造函数分配之前创建我的汤变量?

1 个答案:

答案 0 :(得分:2)

我的XmlParser接收文件名,然后按文件名读取,然后为其他方法创建汤。

在这种情况下,BeautifulSoup实例应该是唯一的类变量。然后,可以在您的方法中将其称为self.soup。无需将file_nameparser_type暴露给任何其他方法,因为它们仅特定于在构造函数BeautifulSoup内部发生的__init__实例化。

from bs4 import BeautifulSoup
from tools import read_file

class XmlParser:    
  def __init__(self, file_name, parser_type):
    xml_file = read_file(file_name)
    self.soup = BeautifulSoup(xml_file, parser_type)

  def method_1(self):
    # access self.soup here

  def method_2(self):
    # access self.soup here
相关问题