简体   繁体   English

python类中的全局变量赋值

[英]Global variable assignment in python class

My XmlParser receive file name and then read by filename and then create my soup for different methods.我的 XmlParser 接收文件名,然后按文件名读取,然后为不同的方法创建我的汤。 I try to make soup global variable.我尝试使汤全局变量。 But I refer to constructor variable and i response: 'NameError: name 'self' is not defined'但我指的是构造函数变量,我的反应是:'NameError: name 'self' is not defined'

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

How can i create my soup variable before constructor assignment?如何在构造函数赋值之前创建我的汤变量?

My XmlParser receive file name and then read by filename and then create my soup for different methods.我的 XmlParser 接收文件名,然后按文件名读取,然后为不同的方法创建我的汤。

In that case the BeautifulSoup instance should be the only class variable.在这种情况下, BeautifulSoup实例应该是唯一的类变量。 In your methods you then can refer to it as self.soup .在您的方法中,您可以将其称为self.soup There is no need to expose file_name and parser_type to any other methods due to they are only specific to the BeautifulSoup instantiation which happens inside of the constructor __init__ .无需将file_nameparser_type暴露给任何其他方法,因为它们仅特定于在构造函数__init__内发生的BeautifulSoup实例化。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM