0

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?

2 Answers 2

1

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)

(Apologies for the truncated initial reply, I was in the middle of typing and my keyboard stopped working.)

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

Comments

1

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"])

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.