I cannot import from another file

Question:

I am making a soccer game. I am new to Python. I am trying to make soccerplayers on a file, then import it to my main game.

Here is soccerplayer.py

class soccerp:
def __init__(self,overall,name,speed,shoot,ballc,defence):
    self.overall = overall
    self.name = name
    self.speed = speed
    self.shoot = shoot
    self.ballc = ballc
    self.defence = defence

Here is soccerkeeper.py

class soccerk:
def __init__(self,overall,name,dive,reactspeed,reach,jump):
    self.overall = overall
    self.name = name
    self.dive = dive
    self.reactspeed = reactspeed
    self.reach = reach
    self.jump = jump

Here is soccerplayerlist.py

from soccerplayer import soccerp
from soccerkeeper import soccerk
#name overall speed shootingpower ballcontrol defence
david = soccerp("david",114,181,179,183,148)
john = soccerp("john",119,179,185,187,151)
soccerplayers = [david,john]

And here is my game.py

import time
from soccerplayerlist import soccerplayers
#name overall speed shootingpower ballcontrol defence

ovr = [120,124,158,132,109] #will edit as the players overalls
teamovr = round(sum(ovr) / len(ovr))

def start():
    print("Please pick your teams name : ")
    team = input(">  ")
    print("")
    time.sleep(1)
    return team

def menu(team):
    print("teams name : " + team)
    print("team overall : " + str(teamovr))

def game():
    team = start()
    #while True:
    teamovr = round(sum(ovr) / len(ovr))
    menu(team)
    print(david.name) #checking if the players were imported from soccerplayerlist.py

game()

when I run the code, It says

NameError: name 'david' is not defined

I think that it didnt import the players, I may be wrong, what am I doing wrong here?

Asked By: Simon Choi

||

Answers:

The name david is not the one you import it is the list of soccerplayers
what you can do is instead of this line.

print(david.name)

do this:

for player in soccerplayers: 
    if player.name == "david":
        david = player

I personaly recommend on pygame it is a library in python which allows to make high level games.

Answered By: ironl1111

The issue is that you’re importing the list and not the values of the list.
If you do

print(soccerplayers[0].name)

You should get the desired result.

Answered By: Ftagliacarne
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.