[英]How to assign a value to a class instance variable?
我正在构建一种编程语言,我需要帮助我在 varObject.py 上有第一个代码片段,在 lexer.py 上有第二个:
变量对象.py
class VariableObject(object):
def __init__(self):
type(self).variables = {}
def set_variable(self, name, value):
self.variables[name] = value
词法分析器.py
from varObject import VariableObject
class Lexer(object):
def __init__(self, source_code):
self.source_code = source_code
def tokenize(self):
varsdb = VariableObject()
varsdb.set_variable("x", 5)
print(varsdb.variables)
预期输出为{"x": 5}
,但实际输出为{}
。
https://docs.python.org/2/tutorial/classes.html#class-objects
我觉得你在这里遗漏了一些关键的代码部分,但你只需要在类的范围内声明一个变量。 查看链接上的示例。 希望这会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.