如何将C#的Servicing类转为Python类并在Adjusted类中实现列表功能?
将C#类转换为Python并实现列表属性
问题描述
我有一个用C#定义的Servicing类,需要将其转换为Python类,同时要实现类似C#中Adjusted类里List<Servicing>的功能。我已经写出了Servicing类的构造函数,请问如何在Adjusted类中像C#那样使用Servicing类的列表?
C#代码示例
class Servicing { public long StatementName{ get; set; } public string City{ get; set; } }
class Adjusted { public List<Servicing> Services{ get; set; } }
已编写的Python Servicing类
class Servicing: def __init__(self): self._StatementName=0.0 self._City= ""
解决方案
1. 优化Servicing类(贴合C#属性特性)
先调整Servicing类的类型匹配(C#中StatementName是long类型,对应Python整数),并用@property装饰器模拟C#的公共属性访问逻辑:
class Servicing: def __init__(self): # 下划线开头表示私有字段,对应C#的私有 backing field self._statement_name = 0 # 改为整数,匹配C#的long类型 self._city = "" # 模拟C#的get/set属性 @property def StatementName(self): return self._statement_name @StatementName.setter def StatementName(self, value): if isinstance(value, int): self._statement_name = value else: raise ValueError("StatementName必须是整数类型") @property def City(self): return self._city @City.setter def City(self, value): if isinstance(value, str): self._city = value else: raise ValueError("City必须是字符串类型")
2. 实现Adjusted类的列表属性
Python原生list可以直接替代C#的List<T>,它是动态容器,能存放Servicing实例并支持所有常用操作。直接在Adjusted类中定义列表属性即可:
class Adjusted: def __init__(self): # 初始化空列表,对应C#的List<Servicing> self.Services = []
3. 使用示例
# 创建Servicing实例 serv1 = Servicing() serv1.StatementName = 12345 serv1.City = "北京" serv2 = Servicing() serv2.StatementName = 67890 serv2.City = "上海" # 向Adjusted实例添加Servicing对象 adjusted = Adjusted() adjusted.Services.append(serv1) adjusted.Services.append(serv2) # 遍历列表中的对象 for serv in adjusted.Services: print(f"StatementName: {serv.StatementName}, City: {serv.City}")
可选:严格类型校验的列表
如果需要确保列表仅能存放Servicing实例,可以自定义继承自list的子类,重写添加方法做类型检查:
class ServicingList(list): def append(self, item): if not isinstance(item, Servicing): raise TypeError("只能添加Servicing类型的对象") super().append(item) def extend(self, items): for item in items: if not isinstance(item, Servicing): raise TypeError("只能添加Servicing类型的对象") super().extend(items) # 改造Adjusted类 class Adjusted: def __init__(self): self.Services = ServicingList()
内容的提问来源于stack exchange,提问作者pulseozara
相关产品推荐
相关产品推荐

