Thundershocked Thundershocked - 3 months ago 8
Python Question

Creating an instance of a class existing in a different file(python)

I am trying to learn how to change my programs so that they use code from multiple python scripts. I have two scripts (these are big files, so cutting them down to only what's needed)

main.py

import pygame
import player #Imports the player.py script
p1 = hero("woody.png",[2,2]) #Creates an instance of hero


player.py

import pygame
import main

class hero:
def __init__(self,image,speed):
self.image = pygame.image.load(image)
self.speed = speed
self.pos = self.image.get_rect()


Running this gives me the following error:

AttributeError: 'module' object has no attribute 'hero'


I'm not quite understanding why it's trying to get an attribute instead of creating an instance. I've tried looking at other examples and how they are solving the problem but when I attempt to apply it to the code above it does not solve my issue.

Answer

Like Athena said above, don't import main into player and player into main. This causes a import loop. Just simply import player into main

Secondly, you must say player.hero() if you want to use the class hero from the player module. Or if you want to just say hero(), you can say from player import*. This tells python to import all the files from player into the namespace main.

Be careful using this though, as a function or class from your player file may conflict with an already exiting function or class, with the same name.

And as a side note, classes in python general have their first letter capitalized.

here is how your files should look:

main.py

import pygame
import player #Imports the player.py script
p1 = hero("woody.png",[2,2]) #Creates an instance of hero

player.py

import pygame

class hero:
    def __init__(self,image,speed):
        self.image = pygame.image.load(image)
        self.speed = speed
        self.pos = self.image.get_rect()#.......etc
Comments