If anyone still has this issue: you get this error when your indentation is goofed.To fix the asked question above, you just have to add a space before the last two functions definitions, that is;
class className(object):
def __init__(self, self1=1,self2=2,self3=3):
self.self1=self1
self.self2=self2
self.self3=self3
def evaluate(self, self5):
print className.func1(self) + className.func2(self)
self.self5=self5
print className.func1(self)
def func1(self):
return self.self1 + self.self5
def func2(self):
self.self4 = self.self1+self.self2+self.self3
return self.self4
just make sure they all have similar indentation, and you are good to go.
Answer from michael ditrick on Stack OverflowIf anyone still has this issue: you get this error when your indentation is goofed.To fix the asked question above, you just have to add a space before the last two functions definitions, that is;
class className(object):
def __init__(self, self1=1,self2=2,self3=3):
self.self1=self1
self.self2=self2
self.self3=self3
def evaluate(self, self5):
print className.func1(self) + className.func2(self)
self.self5=self5
print className.func1(self)
def func1(self):
return self.self1 + self.self5
def func2(self):
self.self4 = self.self1+self.self2+self.self3
return self.self4
just make sure they all have similar indentation, and you are good to go.
Edit:
Your code works fine!
What is the Problem?
I still think it is better to move self4 into the init!
Original
I think the most logical thing would be to define self4 on init:
class className(object):
def __init__(self, self1=1, self2=2, self3=3):
self.self1 = self1
self.self2 = self2
self.self3 = self3
self.self4 = None
#rest of class
hello, i am working on a game using pygame and i am going for an OOP approach, the files are pretty big, i will post only a portion of the code; also i am using pycharm so i know for a fact my identation, typing are alright.. plus i have been coding in python for a while now but i just can't grasp onto this issue :(, so far in the game i am just in the main menu phase and whenever i try to run my code i get an error that my game object (which has a reference to another class including the main menu game loop) has no attribute ''screenWidth'' but it actually does have a variable for my screen.. i just use it in the main menu to set another midWidth variable half of that variable as value
here is the code:
main.py
from game import Game
myGame = Game()
while myGame.running:
myGame.currentMenu.drawMainMenu()
myGame.gameLoop()game.py
import pygame
from menu import MainMenu
class Game:
def __init__(self):
pygame.init()
self.running, self.playing = True, False
self.upKey, self.downKey, self.selectKey, self.backKey = False, False, False, False
self.currentMenu = MainMenu(self)
self.screenWidth = 1280
self.screenHeight = 720
self.gameWindow = pygame.display.set_mode((self.screenWidth, self.screenHeight))
pygame.display.set_caption("Game Prototype")
self.backgroundImage = pygame.image.load('Assets/Images/bg_greek.jpg')
self.backgroundImage = pygame.transform.scale(self.backgroundImage, (1920, 1080))
def gameLoop(self):
while self.playing:
self.checkEvents()
if self.selectKey:
self.playing = False
self.gameWindow.blit(self.backgroundImage, (-600, -300))
pygame.display.flip()
self.resetKeys()
menu.py
import pygame
class Menu:
def __init__(self, game):
self.gameClass = game
self.midWidth = self.gameClass.screenWidth / 2
self.midHeight = self.gameClass.screenHeight / 2
self.showMenu = True
self.selectionX, self.selectionY = 0, 0
def drawSelection(self):
selectSurface = pygame.Surface((260, 100), pygame.SRCALPHA)
selectSurface.fill((50, 50, 50, 175))
selectRect = selectSurface.get_rect()
selectRect.center = (self.selectionX, self.selectionY)
self.gameClass.gameWindow.blit(selectSurface, selectRect)
class MainMenu(Menu):
def __init__(self, game):
Menu.__init__(self, game)
self.hoveredState = "Start"
self.startX, self.startY = self.midWidth, self.midHeight
self.optionsX, self.optionsY = self.midWidth, self.midHeight + 100
self.creditsX, self.creditsY = self.midWidth, self.midHeight + 200
self.quitX, self.quitY = self.midWidth, self.midHeight + 300
self.selectionX, self.selectionY = self.startX, self.startY
def drawMainMenu(self):
self.showMenu = True
while self.showMenu:
self.gameClass.checkEvents()
self.checkInput()
self.gameClass.gameWindow.blit(self.gameClass.backgroundImage, (-600, -300))
self.drawSelection()
self.gameClass.drawText("Play", 72, self.startX, self.startY)
self.gameClass.drawText("Options", 72, self.optionsX, self.optionsY)
self.gameClass.drawText("Credits", 72, self.creditsX, self.creditsY)
self.gameClass.drawText("Quit", 72, self.quitX, self.quitY)
pygame.display.flip()
self.gameClass.resetKeys()
it is not complete though
pyqgis - AttributeError: class instance has no attribute 'class_function' - Geographic Information Systems Stack Exchange
Python "Class has no attribute" - Stack Overflow
Python AttributeError: class object has no attribute - Stack Overflow
python - Getting an AttributeError: <class> has no attribute <method> - Stack Overflow
How to solve the error in Python, "Class object has no attribute_name"?
Which Python method can prevent Attribute Errors?
This is really late, but in case anyone has this problem again, as I did, and looks here, hopefully this helps them.
Some text editors such as Sublime Text occasionally mess up the tabs, so the spacing you see in the text editor is not necessarily what Python sees. Since tabs are important in Python, this can lead to your do_something function being defined within the init function rather than as a separate function. Hence, when you call self.do_something(), Python will not have created the function yet and it will fail.
To fix this, open the file in another text editor. I find the simplest text editors like 'Text Editor' in Ubuntu, 'Notepad' in Windows, or 'TextEdit' in Mac work best. You will likely see immediately where the spacing went wrong and can fix it there. If it is not immediately clear, try deleting the tabs and redoing them.
This fixed the problem for me. Thanks.
I was getting the same error for a long time, I am new to this, but in my function when I remove the underscores from the function name it works fine. I figured underscores are treated in some different way in django.
def getname(self):
return self.name
def getname1(self):
return self.name
def lastseen(self):
return cache.get('seen_%s' % (self.user.username))
def last_seen(self):
return cache.get('seen_%s' % (self.user.username))
The .last_seen() doesn't work, The .lastseen() does, The .getname1() doesn't work, The .getname() does.
To be honest I don't know if anyone does I would love to know why. Thanks
Gold is not an attribute on the Item class, no. It is a subclass, and a global name in its own right. You can import it from your items module:
>>> from items import Gold
>>> Gold
<class 'items.Gold'>
You cannot create an instance of it, because used the wrong name for the Item.__init__ method:
>>> from items import Item
>>> Item.__init__
<slot wrapper '__init__' of 'object' objects>
>>> Item.__init___
<function Item.__init___ at 0x1067be510>
>>> Item('a', 'b', 4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object() takes no parameters
Note that the method you created has three underscores in the name. If you fix that:
class Item():
def __init__(self, name, desc, val):
# ^ ^ 2 underscores on both sides
self.name = name
self.desc = desc
self.val = val
you can create instances of the Gold() class:
>>> Gold()
<items.Gold object at 0x1067cfb00>
>>> gold = Gold()
>>> print(gold.print_info())
Gold
==========
Golden coin.
Value: 5
Now, if you really wanted to create attributes on the Item class, you'll have to add those after you created the class:
class Item():
def __init___(self, name, desc, val):
self.name = name
self.desc = desc
self.val = val
def print_info(self):
return '{}\n==========\n{}\n\nValue: {}'.format(self.name, self.desc, self.val)
Item.gold = Item('Gold', 'Golden coin.', 5)
You don't need to create subclasses for that. You could use the enum module here though:
from enum import Enum
class Item(Enum):
Gold = 'Golden coin.', 5
Silver = 'Silver coin.', 1
def __init__(self, desc, val):
self.desc = desc
self.val = val
def print_info(self):
return '{}\n==========\n{}\n\nValue: {}'.format(self.name, self.desc, self.val)
Here Gold is an attribute of Item:
>>> Item
<enum 'Item'>
>>> Item.Gold
<Item.Gold: ('Golden coin.', 5)>
>>> print(Item.Gold.print_info())
Gold
==========
Golden coin.
Value: 5
>>> Item.Silver
<Item.Silver: ('Silver coin.', 1)>
Here's what you're doing wrong:
Goldis a subclass ofItem, not an attribute of it. Your error is popping up when you try to doItem.Gold. Gold is accessed entirely separately.- You need to instantiate your classes into objects. Once you instantiate an object, you can call your methods on it and access its attributes. Each object stores methods and attributes independently, so one gold coin can have a different name, description, value, or even print its info differently.
- When trying to access a parent class from within a subclass, you just reference the class name directly rather than using
super(). - You have an extra underscore in your
Itemclass's__init__()
So with that in mind, your new main.py should look like this:
from items import Gold
mygold = Gold() # This is where we instantiate Gold into an object
print(mygold.print_info()) # We call the method on the object itself
And your items.py will look like this:
class Item():
def __init__(self, name, desc, val):
self.name = name
self.desc = desc
self.val = val
def print_info(self):
return '{}\n==========\n{}\n\nValue: {}'.format(self.name, self.desc, self.val)
class Gold(Item):
def __init__(self):
Item.__init__(name = "Gold", desc = "Golden coin.", val = str(5))
In your __init__ method, you call self.set_marker() before you set self.markers:
self.set_marker(marker)
self.markers = {
"-" : u"None" ,
"," : u"\u2219"
}
So when set_marker() runs, there is no self.markers yet. Move the call down a line:
self.markers = {
"-" : u"None" ,
"," : u"\u2219"
}
self.set_marker(marker)
Martijn's answer explains the problem and gives the minimal solution. However, given that self.markers appears to be constant, I would make it a class attribute rather than recreating it for every instance:
class TTYFigureData(object):
"""Data container of TTYFigure."""
MARKERS = {
"-": u"None" ,
",": u"\u2219",
}
def __init__(self, x, y, marker='_.', plot_slope=True):
"""Document parameters here as required."""
self.x = x
self.y = y
self.plot_slope = plot_slope
self.set_marker(marker)
def set_marker(self, marker):
"""See also here - usage guidance is also good."""
if marker in [None, "None", u"None", ""]:
self.plot_slope = True
self.marker = ""
elif marker[0] == "_":
self.marker = self.MARKERS[marker[1:]]
else:
self.marker = marker
(note also changes to style in line with the official guidance)
The type of error you describe can be caused simply by mismatched indentation. If the method is at the very bottom of your class, move it up in the class a bit and the problem will become apparent.
When python interpreters run into mismatched indents (like say you started using tabs at the bottom of a file that was indented with spaces), the interpreter will not always throw an error; it can simply ignore the rest of the file. I ran into this just today while updating some old code where the original author used different whitespace chars (that happened to match my Geany tabs), and it threw me for a loop for a lot longer than I'd like to admit. :)
When I ran into this problem, I immediately started checking for unbalanced indents, tabs, etc... Everything seemed correct but the error continued to appear. I walked away, came back, took another look, and DUH..., I found that I had a typo. instead of __init__(), I had typed __inti__(). So check all of your constructor's syntax first.
Your indentation is goofed, and you've mixed tabs and spaces. Run the script with python -tt to verify.
If you’re using python 3+ this may also occur if you’re using private variables that start with double underscore, e.g., self.__yourvariable. Just something to take note of for some of you who may run into this issue.