I've defined class (say for different car types) in file student.py:
class car:
def __init__(self, name, engine, no_of_seats, power_source):
self.name = name
self.engine = engine
self.no_of_seats = no_of_seats
self.power_source = power_source
Then I've imported it to main_project.py
from student import car
I've created, say 3 different car types with data related to the class. Now I would like to print eg only power_source for all 3 car types with at once. My idea was to make list in a list but I doesn't work. Here is piece of my code:
list = [car("Audi", 2.0, 4, "gasoline")], [car("Porsche", 3.0, 7, "gasoline")], [car("Lexus", 2.4, 5, "hybrid")]
Now, I cannot access specific item in a list. I can access whole list but it prints following message:
I get this by using:
print(list[0])
My questions are: - is the way I'm trying to achieve it proper? - is it possible to include in the variable "list" other variables for different car types?
Thank you
There are a few mistakes in your syntax that will cause problems. First, lit's considered bad practice to use "list" as a name for a list, as it overrides the builtin name list. Add an underscore at the end to be pythonic:
list_ = []
Next up, you use square brackets to close off every element of the list, when you should keep every element in the one pair of square brackets.
# Don't do this
list_ = [elem_1], [elem_2], [elem_3],...
# Do this
list_ = [elem_1, elem_2, elem_3]
And then finally, to answer your question, you are filling your list up with car objects. But you want to fill it up with the power_source attributes of the cars objects. So use dot syntax to call the attribute from the car object
list_ = [car("Audi", 2.0, 4, "gasoline").power_source, car("Porsche", 3.0, 7, "gasoline").power_source, car("Lexus", 2.4, 5, "hybrid").power_source]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.