Skip to content Skip to sidebar Skip to footer

Mimic C# Classes In Python

I have the following C# public classes: public class ClassA { public byte var1; public TypeX var2; } public class TypeX { public UInt16 num1; public UInt32 num2;

Solution 1:

Python is a dynamically-typed language. The type of a variable is not determined until it is assigned a value.

The closest you can get to your C# code would be to use type hints, supported in Python 3.5+:

classTypeX:def__init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2

classClassA:def__init__(self, var1, var2: TypeX):
        self.var1 = var1
        self.var2 = var2

But even with type hints, the type of var2 will not be enforced either at compilation time or at run time.

Solution 2:

Python is not a statically typed language, so the answer to:

How can I enforce var2 to be of type TypeX?

is you don't. Of course, you can type-check something, but the Python interpreter won't do it for you, you'll need to explicitly write this rule on your code programatically.

As to the question of how the following:

publicclassClassA
{
    public byte var1;
    publicTypeX var2;
}


publicclassTypeX
{
    publicUInt16 num1;
    publicUInt32 num2;
}

translates to Python, the answer is as simple as:

# You need to explicitly initialize the variables to their correspondent default valuesclassClassA(object):
    def__init__(self):
        self.var1 = bytes() # or b''
        self.var2 = NoneclassTypeX(object):
    def__init__(self):
        self.num1 = int() # or 0
        self.num2 = int() # or 0

Solution 3:

Python is dynamically, not statically, typed, so

classClassA():def__init__(self, var1, var2):
        self.var1 = var1
        self.var2 = var2


classTypeX():def__init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2

is a reasonable thing to do. Just pass an instance of TypeX in when you instantiate your ClassA.

However, as of Python 3.5, you can add optional type hints, e.g.

classTypeX():def__init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2


classClassA():def__init__(self, var1, var2: TypeX):
        self.var1 = var1
        self.var2 = var2

This doesn't affect how the code runs (in particular it doesn't enforce the type at runtime), but it can help developers, and their tools, understand the code better.

Tools like mypy can be used to statically check your code using these optional type hints, especially if you add them to your test suite. The more hints you add, the more mypy can help.

Post a Comment for "Mimic C# Classes In Python"