Jeano Ermitaño Jeano Ermitaño - 1 month ago 8
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 (https://ruslanspivak.com/lsbasi-part1/) 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:

INTEGER, PLUS, EOF = 'INTEGER', 'PLUS', 'EOF'
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.

Examples:
Token(INTEGER, 3)
Token(PLUS '+')
"""
return 'Token({type}, {value})'.format(
type=self.type,
value=repr(self.value)
)

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


I assume that
INTEGER
,
PLUS
, and
EOF
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
object
in the parenthesis means in the Python Class, also the
self
in the parenthesis on the Python function. I also don't know where to put the
__init__
function in C#.

Can someone teach me what the Python code means?

Answer

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.