我的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
如何在构造函数分配之前创建我的汤变量?
答案 0 :(得分:2)
我的XmlParser接收文件名,然后按文件名读取,然后为其他方法创建汤。
在这种情况下,BeautifulSoup
实例应该是唯一的类变量。然后,可以在您的方法中将其称为self.soup
。无需将file_name
和parser_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