You're calling the method "platforms" which is not expecting you to pass it a parameter, and are passing it a parameter. The "locations" list is actually passed to the constructor method of your class, which gets called when you instantiate it. Your "platforms" method is called without parameters and prints it.

Here's how you should (probably) do it:

locations = [0,1]

class Draw:
    def __init__(self, locations):
        self.locations = locations

    def platforms(self):
        print(self.locations)

draw = Draw(locations)    
draw.platforms()
Answer from ag415 on Stack Overflow
Discussions

python - How Do I Pass One List From A Class To Another Class? - Stack Overflow
I am new to using multiple classes in python and I am trying to create a Stock class that holds all the data for a single stock. However, when I try to do the basic initialization of the Stock clas... More on stackoverflow.com
🌐 stackoverflow.com
python - How can I pass a list from one class to another? - Stack Overflow
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_... More on stackoverflow.com
🌐 stackoverflow.com
python - Trying to pass list of variable in class and function in object oriented manner - Stack Overflow
See this question about class-level variables vs instance variables. Furthermore, you are then using double-underscore name-mangling mixed with getters and setters, not really the way things are done in Python. See this questions for more about that ... @juanpa.arrivillaga I understand what you saying but it just prototype so I'm making base model in OOP so that later on I can do my project code on that basis , right now I'm passing variable of array(list... More on stackoverflow.com
🌐 stackoverflow.com
May 20, 2017
python - passing list to a function in a class - Stack Overflow
I'm learning Python. I'm not sure how to pass a list to function in a class. More on stackoverflow.com
🌐 stackoverflow.com
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 45172544 › passing-list-of-argument-to-class
python - passing list of argument to class - Stack Overflow
maybe something like def __init__(self, **kwargs) so you can pass a dict of attributes when initializing your class instance (look at **kwargs)
🌐
W3Schools
w3schools.com › python › gloss_python_function_passing_list.asp
Python Passing a List as an Argument
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.7 documentation
Actually, you may have guessed the answer: the special thing about methods is that the instance object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s instance object before the first argument. In general, methods work as follows. When a non-data attribute of an instance is referenced, the instance’s class is searched.
🌐
Reddit
reddit.com › r/learnpython › is it possible to pass a list to class method without instantiating the class?
r/learnpython on Reddit: Is it possible to pass a list to class method without instantiating the class?
February 10, 2022 -

As of late, I’ve been playing around a lot with BeautifulSoup. I find that anytime I call ‘find_all()’ having to loop through the elements to ‘.prettify()’ I let out a sigh. I figured I’d give writing a simple package a shot which would apply ‘.prettify()’ to the list elements and print. My goal is to have this method applied without having to instantiate the class.

For example:

import custom_prettify as purrty 

# etc etc…

tables = soup.find_all('table')

#call method
tables.purrty()

# output:

# [list of prettify() html tables]

🌐
Stack Overflow
stackoverflow.com › questions › 37491838 › passing-a-list-of-arguments-into-a-class
python - Passing a list of arguments into a class - Stack Overflow
At runtime self.points will be a list containing whatever values you passed in. Same with self.angels. Note that if your list contains objects and not just primitives you may be passing in a pointer in your list and not the actual object. ... Sign up to request clarification or add additional context in comments.
🌐
Python.org
discuss.python.org › python help
Passing class argument and checking for list type - Python Help - Discussions on Python.org
August 19, 2023 - I am trying to write a normalizer that would convert a given data (e.g. either str or list[str]) to a given output (let’s consider pathlib.Path and list[pathlib.Path]). The interface that I have in mind is something like: def normalize(cls: Type[T], data: str | list[str]) -> T: ... input_str = "./path" input_list_str = [ "./path" ] out = normalize(pathlib.Path, input_str) # normalize(pathlib.Path, input_list_str) # Fail normalize(list[pathlib.Path], input_str) == normalize(list[pathlib.Path...
Top answer
1 of 1
1

I think the problem here is organization. Since Advisor inherits from Person, there is no self.selectedCourses attribute to be had. What I would do is one of two things:

  1. Store Student instances as a dict within an Advisor_instance.advisees attribute, so you can look-up by name
  2. Pass the Student instance to the method itself to be able to look up that attribute

1

class Advisor(Person):
    def __init__(self, name, advisee=None):
        print("I'm here.")
        Person.__init__(self, name)
        self.advisees = {advisee.name: advisee} if advisee else {}

    def add_advisee(self, student_inst):
        if student_inst.name in self.advisees:
            raise KeyError("Entry already exists")
        self.advisees[student_inst.name] = student_inst

    # Easy name lookup and returns the list
    def get_course_list(self, name):
        # Will raise keyerror if name not in advisees
        return self.advisees.[name].selectedCourses    

alice = Student("Alice", 98980)
cindy = Advisor("Cindy", alice)

cindy.get_course_list('alice')

Personally, I think this first implementation is a bit more intuitive for your use case. An advisor can have many advisees, and storing the instances of Student allows a simple name lookup, you don't need to pass things around.

Extending this more specifically to what you are looking for:

class Advisor(Person):
    def __init__(self, name, advisee=None):
        print("I'm here.")
        Person.__init__(self, name)
        self.advisees = {advisee.name: advisee} if advisee else {}

    def add_advisee(self, student_inst):
        if student_inst.name in self.advisees:
            raise KeyError("Entry already exists")
        self.advisees[student_inst.name] = student_inst
    
    def approveSelectedCourse(self, student_name):
        # don't set a self attr here
        # will still raise a KeyError for missing advisees
        var1 = self.advisees[student_name].finishedCourses

        # Do things with var1

2


class Advisor(Person):
    def __init__(self, name):
        print("I'm here.")
        Person.__init__(self, name)

    def get_course_list(self, student_inst):
        return student_inst.selectedCourses


alice = Student("Alice", 98980)
cindy = Advisor("Cindy")

cindy.get_course_list(alice)

This way would work better if the instance of Advisor was more general, i.e. there doesn't need to be a specific Advisor, only that they are able to accomplish Advisor-like methods. In that case, the name attribute could drop and the methods could be static, in which case, why have the class?

Top answer
1 of 2
1

That []-default-value thing catches a lot of people out, so I'll cover it first. When Python's running your code, it does this:

def append_two(a=[]):
    a.append(2)
    return a

print(append_two())
print(append_two([1, 2, 3])
print(append_two())

Oh, look! A function definition! Ok, so the default value is []; let's evaluate that... And some code, but let's not run that yet.

def append_two(a=<list object at 0x34FE2910>):
    ...

print(append_two())
print(append_two([1, 2, 3])
print(append_two())

Ok, now let's run it. Appending 2 to [] makes [2], so we print("[2]"). Appending 2 to [1, 2, 3] makes [1, 2, 3, 2], so we print("[1, 2, 3, 2]"). Appending 2 to [2] makes [2, 2], so we print("[2, 2]"). And done!

[2]
[1, 2, 3, 2]
[2, 2]

Why does this happen? Well, it was that first stage. Python, when evaluating the function, created The Default List for append_two. And that means that, if you don't pass in a list, it'll always append to that one. That list will slowly grow over time, as more 2s keep getting added to it.

The reason for this is consistency. When you run the function, only the stuff inside the function will run. Nowhere inside the function does it say "make a new list", so it doesn't. If you want it to, you have to tell it to, like so:

def append_two(a=None):
    if a is None:
        a = []  # Make a new list
    a.append(2)
    return a

This is clunky and annoying, but that's the price you have to pay for consistency. The alternatives are worse.


Now onto your main problem. I'll simplify it slightly.

class DemoClass:
    def __getitem__(self, index):
        return index
dataset = DemoClass()

style_clms = ["X", "Y"]
print(dataset[style_clms])

This prints ['X', 'Y']. Let's see what dataset["X", "Y"] prints:

>>> print(dataset["X", "Y"])
('X', 'Y')

Ok... This is called a tuple. It's easy enough to convert a list into a tuple:

>>> print(dataset[tuple(style_clms)])
('X', 'Y')

Hooray! We've successfully replicated dataset["X", "Y"] for arbitrary things! :-) This hopefully solves your problem.

2 of 2
0

Just flatten the list with this:

import itertools
flat_list = list(itertools.chain(*list2d))

or

flat_list = [item for sublist in l for item in sublist]
🌐
Stack Overflow
stackoverflow.com › questions › 57966313 › passing-a-list-to-a-method-inside-a-class-from-another-class-in-order-to-modify
algorithm - Passing a list to a method inside a class from another class in order to modify said list and pass back to the original class in Python - Stack Overflow
and finally with (self, dealed_cards = []) result: still not passing in the list dealed_cards from inside the function · Here is a test block of code I broke off from the main program in order to test this method. class deal_card(object): def __init__(self): pass def deal_card_out(self, dealed_cards = []): print("This is a test print statement at the beginning of this method to test that dealed_cards was passed in correctly.") print(dealed_cards) card_one_face_value = 'Seven' card_one_suit_value = 'Clubs' for _ in dealed_cards: if card_one_face_value == [_[0]]: print(f"This is a test print st
🌐
Toppr
toppr.com › guides › computer-science › programming-with-python › lists › lists-as-arguments
Python Passing a Lists as Arguments: Definition and Concepts
May 25, 2021 - In Python, we can easily expand the list, tuple, dictionary as well as we can pass each element to the function as arguments by the addition of * to list or tuple and ** to dictionary while calling function.
Top answer
1 of 1
1

It looks like you are trying to run DataProcessing and get parameter values from ClearRoadsInputTool.

That won't work. You can't get parameters from another tool.

You can only collect parameters in one tool and pass them to a second tool. The user will never see the second tool though, so you will need to collect all parameter values in the first tool.

So in your case, you would run ClearRoadsInputTool to collect the parameters and then pass those parameter values to DataProcessing.

The arcpy way of doing this is to import the toolbox containing the tool you want to call.

E.g.

import os
import arcpy

class Toolbox(object):
    def __init__(self):

       self.label = "Toolbox"
       self.alias = "ClearRoadsScript"

       # List of tool classes associated with this toolbox
       self.tools = [ClearRoadsInputTool, DataProcessing]


class ClearRoadsInputTool(object):
    def __init__(self):

        self.label = "Input Data Layers"
        self.description = ""
        self.canRunInBackground = False


    def getParameterInfo(self):

        inputPlowRoutes = arcpy.Parameter(
            displayName = "Input Plow Routes",
            name = "Plow Routes",
            datatype = "GPFeatureLayer",
            parameterType = "Required",
            direction = "Input")
    
        inputWorkspace = arcpy.Parameter(
            displayName = "Input Workspace",
            name = "Workspace",
            datatype = "DEWorkspace",
            parameterType = "Required",
            direction ="Input")

        parameters = [inputPlowRoutes, inputWorkspace]
        return parameters

    def execute(self, parameters, messages):
        plowroutes = parameters[0].value
        workspace = parameters[1].valueAsText
        with arcpy.EnvManager(workspace=workspace):
            fcs = [os.path.join(workspace, fc) for fc in arcpy.ListFeatureClasses()]

        arcpy.ImportToolbox(__file__)
        arcpy.DataProcessing_ClearRoadsScript(plowroutes, fcs)

class DataProcessing(object):
    def __init__(self):
    
        self.label = "Data Processing"
        self.description = ""
        self.canRunInBackground = False

    def getParameterInfo(self):

        inputPlowRoutes = arcpy.Parameter(

            displayName = "Input Plow Routes",
            name = "plow_routes",
            datatype = "GPFeatureLayer",
            parameterType = "Required",
            direction = "Input")
    
        inputLayers = arcpy.Parameter(

            displayName = "Input Layers",
            name = "input_layers",
            datatype = "GPFeatureLayer",
            parameterType = "Required",
            direction = "Input",
            multiValue=True)
    
        params = [inputPlowRoutes, inputLayers]
        return params
 

    def execute(self, parameters, messages):

        arcpy.env.overwriteOutput = True
        arcpy.CheckOutExtension("spatial")

        Plow_Routes = parameters[0].value
        InputLayers =  parameters[1].values

        messages.addMessage(Plow_Routes)
        messages.addMessage(InputLayers)

However, I think that's not the best way to do this as users will have to know to run the ClearRoadsInputTool not the DataProcessing tool.

It would be better to have a DataProcessing function which users never see.

import os
import arcpy

class Toolbox(object):
    def __init__(self):

       self.label = "Toolbox"
       self.alias = "ClearRoadsScript"

       # List of tool classes associated with this toolbox
       self.tools = [ClearRoadsInputTool]


class ClearRoadsInputTool(object):
    def __init__(self):

        self.label = "Input Data Layers"
        self.description = ""
        self.canRunInBackground = False


    def getParameterInfo(self):

        inputPlowRoutes = arcpy.Parameter(
            displayName = "Input Plow Routes",
            name = "Plow Routes",
            datatype = "GPFeatureLayer",
            parameterType = "Required",
            direction = "Input")
    
        inputWorkspace = arcpy.Parameter(
            displayName = "Input Workspace",
            name = "Workspace",
            datatype = "DEWorkspace",
            parameterType = "Required",
            direction ="Input")

        parameters = [inputPlowRoutes, inputWorkspace]
        return parameters

    def execute(self, parameters, messages):
        plowroutes = parameters[0].value
        workspace = parameters[1].valueAsText
        with arcpy.EnvManager(workspace=workspace):
            fcs = [os.path.join(workspace, fc) for fc in arcpy.ListFeatureClasses()]

        DataProcessing(plowroutes, fcs)


def DataProcessing(inputPlowRoutes, inputLayers):

    arcpy.env.overwriteOutput = True
    arcpy.CheckOutExtension("spatial")

    arcpy.AddMessage(inputPlowRoutes)
    arcpy.AddMessage(inputLayers)