【问题标题】:passing an array of pointers to python class将指针数组传递给 python 类
【发布时间】:2012-10-28 02:51:33
【问题描述】:

我是 python 新手。我熟悉 C++。我会将流动的 C++ 代码转换为 python。

class School{
    School(char *name, int id, Student* pointers){
    {
        this.name=name;
        this.weapon=weapon;
        this.students=pointers;
    }
    print(){
        for(int i=0;i<10;i++){
            this.students.print();
        }
    }
};

如您所见,我正在尝试将指针传递给 Student 类型的对象数组 我不确定python是否允许我传递指针。这就是我在python中所做的

class School():
    def __init__(self, name, *students):
        self.name=name
        self.students=students

    def display(self):
        for student in self.students
            student.display()

【问题讨论】:

  • 为什么不在更高范围内拥有一个数组并访问它?
  • 数组是私有类变量
  • 在python中没有私有变量这样的东西。
  • 我发现了我的问题。它在 for 循环的末尾。我必须输入“:”
  • 因为我是 python 新手,所以我认为有些不同。我以为在传递数组时我必须做点什么

标签: python class pointers for-loop python-2.7


【解决方案1】:

在 python 中,将整个列表传递给构造函数是完美的。
无论如何,Python 都会将该列表作为参考传递。

class School():
    def __init__(self, name, students):
        self.name=name
        self.students=students

    def display(self):
        for student in self.students
            student.display()

在这种情况下,self.students 是对原始 students 列表的引用


一个很好的测试方法是下面的代码:

original = ['a','b']

class my_awesome_class:
    def __init__(self, a):
        self.my_list = a

    def print_list(self):
        self.my_list.append("my_awesome_class")
        print(self.my_list)

my_class = my_awesome_class(original)

print (original)
my_class.print_list()
print (original)

如需额外阅读,您可能需要查看python variable names from a c perspective

【讨论】:

  • 我看到你没有 for 循环。你有一个对象 b.您正在打印对象。您的对象 b 具有树元素“a”、“b”和“lol”。我想打印三个或更多对象。每个对象都有不同的名称。
  • @user1061392 我一次打印整个列表以使其更易于阅读,这是一个概念证明,而不是您正在做什么的示例。如果您愿意,可以使用 for 循环打印列表的元素。
  • 我的问题是“for student in self.students”中有“SyntaxError: invalid syntax”
  • @user1061392 这听起来很像应该是一个不同的问题。但你可能忘记了:
  • 谢谢。我刚看了你的评论。我错过了“:”。有时这些小东西最难找到
【解决方案2】:

Python 没有指针。或者更确切地说,Python 中的 一切 都是一个指针,包括名称、列表中的条目、属性……Python 是一种“传递引用”的语言。

这里有几个简单的例子:

In [1]: a = ['hello', tuple()]  # create a new list, containing references to
                                # a new string and a new tuple. The name a is
                                # now a reference to that list.

In [2]: x = a  # the name x is a reference to the same list as a.
               # Not a copy, as it would be in a pass-by-value language

In [3]: a.append(4)  # append the int 4 to the list referenced by a

In [4]: print x
['hello', (), 4]  # x references the same object

In [5]: def f1(seq):  # accept a reference to a sequence
   ...:     return seq.pop()  # this has a side effect:
                              # an element of the argument is removed.

In [6]: print f1(a)  # this removes and returns the last element of
4                    # the list that a references

In [7]: print x  # x has changed, because it is a reference to the same object
['hello', ()]

In [8]: print id(a), id(x)
4433798856 4433798856  # the same

In [9]: x is a  # are x and a references to the same object?
Out[9]: True

Python 提供了高级构造来执行您需要在 C 中进行指针运算的事情。因此您无需担心给定变量是否为指针,就像您无需担心内存管理一样。

【讨论】:

  • 如何传递对象数组并使用 for 循环打印每个对象
  • 我知道 Python 中的一切都是指针,但它不允许我执行 for 循环
  • for obj in lst: print obj。为此,您需要确保列表中的对象具有__repr____str__ 方法。内置类型已经有了,但您需要为自定义对象定义自己的。
  • 出于我认为 this answer 解释得很清楚的原因,将 Python 描述为“传递引用”语言并不完全合理。
  • 为你们俩澄清一下:由于 OP 显然是 Python 的新手,我决定在我的回答中用一些知识上的严谨性换取解释的简单性。
【解决方案3】:

您输入的内容基本上就是您想要的,但有一个关键的区别。注意学生之前没有星号:

class School():
    def __init__(self, name, students):
        self.name=name

        self.students=students

    def display(self):
        for student in self.students:
            student.display()

这意味着您将像这样实例化一个学校(为学生构建一个构造函数):

s1 = Student('Bob')
s2 = Student('Fill')

school = School("Generic School",[s1,s2])

如果您的 __init__ 方法看起来像 def __init__(self, name, *students):,那么您将实例化 完全相同的学校

s1 = Student('Bob')
s2 = Student('Fill')

school = School("Generic School",s1,s2)

原因是__init__ 中的*students(这适用于任何方法)意味着“将其余传递的非关键字参数放入student 列表中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 2018-04-15
    • 2013-02-15
    • 1970-01-01
    • 2012-01-24
    • 2016-09-15
    相关资源
    最近更新 更多