Home > Enterprise >  Can I add an attribute to a list in python?
Can I add an attribute to a list in python?

Time:12-08

Former js dev here. I am writing a program (for school) and I need a list filled with turtle objects. However, I need to add an attribute "speed" to the list.

I know in javascript, it would be something like:

let a = [];
a.speed = 5

And then I would make a factory function for turtles using that speed attribute. I tried this in python:

turtles = [Turtle()]
turtles.speed = 10

And it threw the error: 'AttributeError: 'list' object has no attribute 'speed' on line 9'

Any Suggestions?

CodePudding user response:

An AttributeError: list object has no attribute x is caused by trying to access an attribute or method that does not exist for a particular object. In your case, you are trying to access the speed attribute of the list object no the turtle object and the list class does not have a speed attribute.

In order to set the speed attribute to 10 for all turtle objects in the list you can do something like this:

import turtle

# create an empty list to hold all of the turtles
turtles = []

# creating some turtle objects and adding them to the turtles list
# this only adds 10 turtles, you can change this number to the amount of turtles that you need
for i in range(10):
    t = turtle.Turtle()
    turtles.append(t)

# setting the speed of each turtle in the list
for t in turtles:
    setattr(t, 'speed', 10) 

What I did here was use the setattr() function to set the speed attribute of each turtle by iterating through the list of turtles in a for loop and changing the speed attribute of each one.

CodePudding user response:

Python doesn't have Object like Javascript. Instead, it has Dictionary. to create a Dictionary in your case:

turtles = {}
turtles["speed"] = 10

print(turtles)
# access turtle's speed 
print(turtles["speed"])

CodePudding user response:

Sorry, was in the middle of typing an answer and my keyboard fritzed! You'll want to subclass list. Classes are much more common in Python than in JS, though like JS you can choose to write in (almost) any paradigm you want to. Here's a simple example, though you could get fancier.

class MyList(list):
    def __new__(self, *args):
        return super(MyList, self).__new__(self, args)

    def __init__(self, *args):
        list.__init__(self, args)


foo = MyList(1, 2, 3)
foo.speed = 5
print(foo)
print(foo.speed)
  • Related