Jeano Ermitaño Jeano Ermitaño - 3 months ago 20
Python Question

Python Classes (object) and Functions (self) in C#

I'm currently building my own interpreter for a custom language using C#. I'm currently following this guide ( which I think would help me make my simple interpreter. However, the guide has code for Python, and I don't know a single thing in Python.

I'm having trouble with this bit of code in the guide:

class Token(object):
def __init__(self, type, value):
# token type: INTEGER, PLUS, or EOF
self.type = type
# token value: 0, 1, 2. 3, 4, 5, 6, 7, 8, 9, '+', or None
self.value = value

def __str__(self):
"""String representation of the class instance.

Token(INTEGER, 3)
Token(PLUS '+')
return 'Token({type}, {value})'.format(

def __repr__(self):
return self.__str__()

I assume that
, and
are global constants. But in my code I can't create something similar to this, so I just create the constant in the function where I need it like
const string INTEGER = "INTEGER"
. Is this correct?

Second problem: I can't figure out how classes and functions work in Python. From the code above, I created this in C#:

public class Token {
public string tokenStr(string type, string value)
return "Token(" + type + "," + value + ")";

I don't understand what
in the parenthesis means in the Python Class, also the
in the parenthesis on the Python function. I also don't know where to put the
function in C#.

Can someone teach me what the Python code means?


Yeah, these are global vars. Your approach is just fine.
The 'object' in the parentheses is an inheritance from the class 'object'. As far as you care in this case, you can ignore it.
The self in the parentheses is just python syntax, self is the equivalent for 'this' in C#, and you have to specify it in the method's signature. Again, you can ignore it.
init is simply the constructor of the class.