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