【问题标题】:How do I make a struct point in python?如何在 python 中创建一个结构点?
【发布时间】:2022-11-10 01:19:46
【问题描述】:

我正在基于https://www.youtube.com/watch?v=zH_omFPqMO4 在 Pygame 中制作俄罗斯方块克隆,我需要知道如何转

struct Point
{int x,y;} a[4],b[4];

从 C++ 到 Python。

【问题讨论】:

  • 只是不要尝试将 C++ 逐行转换为 Python,这通常是行不通的。尝试了解 C++ 代码在 python 中的重写。不同的语言以不同的方式工作。即使代码看起来相似,python 和 C++ 处理对象的内存和生命周期也是不同的。所以通常:学习两种语言,尝试理解算法,然后你可以用目标语言重写。

标签: python c++ tetris


【解决方案1】:

因此,C++ 代码struct point {int x, y} a[4], b[4] 创建了一个新的structure,这是一个具有两个整数xy 的数据类型。 a[4]b[4] 是两个创建的 point 类型的数组,每个数组的大小为 4

要在 python 中复制structure,我们可以使用class

例子:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

a = []
b = []

# Creating an instance of the Point object
myPoint = Point(5, 6)

# Adding said point to our array
a.append(myPoint)

【讨论】:

    【解决方案2】:

    所以一个类只是 C++ 中的结构?

    struct Point{int x,y;}a[4]b[4]
    

    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
    a = []
    b = []
    
    # Creating an instance of the Point object
    myPoint = Point(5, 6)
    
    # Adding said point to our array
    a.append(myPoint)
    b.append(myPoint()
    

    ?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 2016-04-11
      • 1970-01-01
      • 2011-08-25
      • 2012-06-10
      相关资源
      最近更新 更多