在 Python 中模仿 C# 类 [英] Mimic C# classes in Python
问题描述
我有以下 C# 公共类:
public class ClassA
{
public byte var1;
public TypeX var2;
}
public class TypeX
{
public UInt16 num1;
public UInt32 num2;
}
(这个例子中的名字是简化的,不是真实的)
(Names are simplified for this example and are not real)
这在 Python 中会是什么样子?具体来说,如何将 var2
创建为 TypeX
的实例?
What would this look like in Python? Specifically, how would var2
be created as an instance of TypeX
?
到目前为止,我已经提出了以下 Python 类:
So far I have the come up with the following Python classes:
class ClassA():
def __init__(self, var1, var2 = TypeX):
self.var1 = var1
self.var2 = var2
class TypeX():
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
但是,我几乎 100% 确定这是不正确的.ClassA
是否应该继承TypeX
?任何指导或解释将不胜感激!
However, I am nearly 100% sure this is not correct. Should ClassA
inherit TypeX
? Any guidance or explanations would be appreciated!
推荐答案
Python 不是静态类型语言,因此答案:
Python is not a statically typed language, so the answer to:
如何强制 var2 为 TypeX 类型?
How can I enforce var2 to be of type TypeX?
是你没有.当然,您可以对某些内容进行类型检查,但 Python 解释器不会为您执行此操作,您需要以编程方式在代码中明确编写此规则.
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.
关于如何的问题如下:
public class ClassA
{
public byte var1;
public TypeX var2;
}
public class TypeX
{
public UInt16 num1;
public UInt32 num2;
}
翻译成Python,答案很简单:
translates to Python, the answer is as simple as:
# You need to explicitly initialize the variables to their correspondent default values
class ClassA(object):
def __init__(self):
self.var1 = bytes() # or b''
self.var2 = None
class TypeX(object):
def __init__(self):
self.num1 = int() # or 0
self.num2 = int() # or 0
这篇关于在 Python 中模仿 C# 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!