[英]C# class to Python class
我有一個 class 在 C# 中定義為服務,我需要將此代碼轉換為 Python。那么我如何將服務 class 轉換為 python 中的列表數據類型,然后在調整后的 883981812195 中使用它?
class Servicing
{
public long StatementName{ get; set; }
public string City{ get; set; }
}
現在這個class在另一個class中使用調整
class Adjusted
{
public List<Servicing> Services{ get; set; }
}
對於 Servicing class,我可以像這樣定義構造函數,然后也定義它的 setter 和 getter。
class Servicing:
def __init__(self):
self._StatementName=0.0
self._City= ""
但是我如何使用這個 Servicing class,就像它在 Adjusted class 中的使用方式一樣?
Python 不需要 setter 或 getter,因為所有 class 屬性和方法都是公共的。 相反,值作為參數提供給__init__
並且 class 以這種方式初始化。 列表幾乎一樣簡單,只需使用 .append 添加新值或使用.append
擴展另一個可迭代.extend
class Servicing:
# Default values for class
def __init__(self, StatementName=0.0, City=""):
self.StatementName = StatementName
self.City = City
class Adjusted:
def __init__(self, Services=[]):
self.Services = []
self.Services.extend(Services)
def add_service(self, StatementName=0.0, City=""):
new_servicing = Servicing(StatementName, City)
self.Services.append(new_servicing)
a_servicing = Servicing(1.2, "London")
print(Servicing.City)
a_servicing.City = "Boston"
print(Servicing.City)
當你更熟悉 python 時,有一種方法可以使用 @property@property
器實現 getter/setter。
class Adjusted:
def __init__(self):
self.Services = None
class Servicing:
def __init__(self):
self.StatementName = 0
self.City = None
對Python了解不多,不過應該是像上面這樣的吧。
請忽略編譯錯誤,因為我不是來自 Python 背景。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.