Python中并沒有直接支持結構體的數據類型,但可以通過使用類來模擬結構體的操作。在類中定義屬性來表示結構體中的字段,并可以定義方法來操作這些字段。常見的結構體操作包括:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 4)
print(p.x) # 輸出3
print(p.y) # 輸出4
p = Point(3, 4)
p.x = 5
print(p.x) # 輸出5
p1 = Point(3, 4)
p2 = Point(0, 0)
p2.x = p1.x
p2.y = p1.y
print(p2.x, p2.y) # 輸出3 4
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
p1 = Point(3, 4)
p2 = Point(3, 4)
print(p1 == p2) # 輸出True