2

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()
5
  • why not just have an array in a higher scope and access that? Commented Nov 7, 2012 at 23:35
  • the array is private class variable Commented Nov 7, 2012 at 23:37
  • in python there is no such thing as a private variable. Commented Nov 7, 2012 at 23:41
  • I find my problem. it was in end of for loop. I have to put ":" Commented Nov 8, 2012 at 0:26
  • since I am new to python, I assumed that there is something different. I thought I have to do something when passing the array Commented Nov 8, 2012 at 0:28

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

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 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.
My problem is that I have "SyntaxError: invalid syntax" in "for student in self.students"
@user1061392 This sounds a lot like it should be a different question. But you probably forgot the :
Thank you. I just read your comment. I am missing the ":". Some times these small things are the hardest to find
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.

8 Comments

How can I pass the array of objects and print every object using a for loop
I understand that everything in Python is a pointer but it does not allow me to do the for loop
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.
For reasons that I think this answer explains very clearly, it doesn't quite make sense to describe Python as a 'pass-by-reference' language.
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.
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.