Jake Rayner
Jake Rayner

Reputation: 32

How can I pass a list from one class to another?

I'm still pretty new to python so, as said in the title, I'm trying to pass a list from inside one class to another class.

For example:

class class_One:
  def__init__(self)
     list_wanting_to_be_passed = [1,2,3,4,5]

class class_Two:
  def __init__(self,list1):
     self.list1 = list1
     print(self.list1)

class_One()

As shown in the example I want a list from class one to be passed to class two so that it can then be used (printed in the example).

Upvotes: 0

Views: 734

Answers (1)

Selcuk
Selcuk

Reputation: 59184

You should make list_wanting_to_be_passed an instance attribute so that you can keep a reference to it:

class ClassOne:
    def __init__(self):
        self.list_wanting_to_be_passed = [1, 2, 3, 4, 5]


class ClassTwo:
    def __init__(self, list1):
        self.list1 = list1


object_one = ClassOne()
object_two = ClassTwo(object_one.list_wanting_to_be_passed)
print(object_two.list1)

Upvotes: 2

Related Questions