1

I am new to python. I am familiar with C++. I would convert the flowing C++ code to 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();
        }
    }
};

As you see I am trying to pass a pointer to an array of objects of type Student I am not sure if python allow me to pass pointers. This is what I did in python

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

    def display(self):
        for student in self.students
            student.display()
user1061392
  • 304
  • 3
  • 14

3 Answers3

0

In python it is perfectly find to pass a whole list into the constructor.
Python will pass the list in as a reference anyway.

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

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

in this case self.students is a reference to the original students list


a good way to test this is the following code:

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)

For extra reading you may want to look at python variable names from a c perspective

Serdalis
  • 10,296
  • 2
  • 38
  • 58
  • I see that you do not have a for loop. You have one object b. you are printing the object. your object b has tree elements 'a','b', and "lol". I want to print three or more objects. Every object has different name. – user1061392 Nov 07 '12 at 23:48
  • @user1061392 I am printing the whole list at once to make it easier to read, this is a proof of concept not an example of what you are doing. You can use a for loop to print the elements of the list if you wish. – Serdalis Nov 07 '12 at 23:50
  • My problem is that I have "SyntaxError: invalid syntax" in "for student in self.students" – user1061392 Nov 07 '12 at 23:55
  • @user1061392 This sounds a lot like it should be a different question. But you probably forgot the `:` – Serdalis Nov 07 '12 at 23:57
  • Thank you. I just read your comment. I am missing the ":". Some times these small things are the hardest to find – user1061392 Nov 08 '12 at 00:30
0

Python doesn't have pointers. Or, rather, everything in Python is a pointer, including names, entries in lists, attributes... Python is a 'pass-by-reference' language.

Here are a few simple examples:

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 provides high-level constructs for doing things that you would need pointer arithmetic for in C. So you never need to worry about whether a given variable is a pointer or not, just like you never need to worry about memory management.

Benjamin Hodgson
  • 42,952
  • 15
  • 108
  • 157
  • How can I pass the array of objects and print every object using a for loop – user1061392 Nov 08 '12 at 00:07
  • I understand that everything in Python is a pointer but it does not allow me to do the for loop – user1061392 Nov 08 '12 at 00:08
  • `for obj in lst: print obj`. For this to work you need to make sure the objects in your list have a `__repr__` or `__str__` method. The built-in types already have them, but you need to define your own for custom objects. – Benjamin Hodgson Nov 08 '12 at 00:09
  • Note that the `for` loop in Python iterates over the _members_ of a sequence. In C you do something like `for(int i=0;i<100;i++){l[i]}` to sequentially get the members of an array; Python does this for you. It may seem a little confusing at first but it makes for much more readable code. – Benjamin Hodgson Nov 08 '12 at 00:13
  • 1
    For reasons that I think [this answer](http://stackoverflow.com/a/12440337/577088) explains very clearly, it doesn't quite make sense to describe Python as a 'pass-by-reference' language. – senderle Nov 08 '12 at 00:32
  • You seem to use `pointer` and `reference` interchangeably, this is incorrect. – Serdalis Nov 08 '12 at 00:32
  • @Serdalis: you're right about pointers and references being different concepts, but for the purposes of illustration I thought it'd be simpler not to draw the distinction. – Benjamin Hodgson Nov 08 '12 at 01:22
  • 1
    To clarify for both of you: since OP is clearly new to Python I decided to trade some intellectual rigour for explanatory simplicity in my answer. – Benjamin Hodgson Nov 08 '12 at 01:33
0

What you've typed is basically what you want, with a key difference. Notice no star before students:

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

        self.students=students

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

This means you'll instantiate a school like this (making up a constructor for students):

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

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

If you're __init__ method looks like def __init__(self, name, *students):, then you would instantiate the exact same school with:

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

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

The reason is that the *students in __init__ (and this holds true for any method) means "Take the rest of the passed, non-keyword arguments and stick them in the student list.

Arion
  • 1,792
  • 2
  • 18
  • 29