简体   繁体   中英

How to assign a value to a class instance variable?

I am building a programming language and I need help I have the first code snippet on varObject.py and the second on lexer.py:

varObject.py

class VariableObject(object):

    def __init__(self):
        type(self).variables = {}

    def set_variable(self, name, value):
        self.variables[name] = value

lexer.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)

The expected output is {"x": 5} , but the actual output is {} .

https://docs.python.org/2/tutorial/classes.html#class-objects

I feel like you are missing some key parts of code here but you just have to declare a variable in the scope of the class. Look at the example on the link. Hopefully this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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