1

I know this C# code:

public class ClassA
{
    public byte var1;
}

can be converted to this Python code:

class ClassA(object):
    def __init__(self):
        self.var1 = bytes() # or b''

but what if var1 were instead a byte array as follows:

public byte[] var1;

Normally, I would do:

[bytes(i) for i in myList]

but no such variable like myList exists in this case to fill that position, leaving me with [bytes(i) for i in ] which is obviously syntactically invalid.

Related to Mimic C# classes in Python

1 Answer 1

2

bytes() is not the equivalent of a C# byte. There is no direct equivalent of a C# byte in Python; the closest would be an ordinary int. I would consider the most direct translation of that C# class to be

class ClassA(object):
    def __init__(self):
        self.var1 = 0

bytes objects are immutable sequences of bytes. If you want a mutable sequence of bytes, either a bytearray or an ordinary list would be appropriate, or an array.array array. I'd probably go with the list unless I had specific reason to do otherwise, really:

class ClassA(object):
    def __init__(self):
        self.var1 = []

Note that bytearray and bytes represent sequences of unsigned bytes; their elements go from 0 to 255, not from -128 to 127. An array.array('b') would be a sequence of signed bytes.

Sign up to request clarification or add additional context in comments.

5 Comments

What makes 0 more concise than bytes() or b''? I am less familiar with this topic.
@CtrlS: It's not about what's more concise; it's about writing code that actually means the right thing. (0 is more concise, being 1 character instead of 7 or 3, but that doesn't matter.)
Maybe concise was the wrong word...what I'm really asking I guess then is how do bytes() and 0 differ?
@CtrlS: bytes() is an immutable sequence of 0 bytes. 0 is the integer 0.
So the difference is that bytes() implies multiple bytes, whereas 0 is obviously a single value. Okay, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.