[英]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.