HP Forums
Python OOP broken? - Printable Version

+- HP Forums (https://www.hpmuseum.org/forum)
+-- Forum: HP Calculators (and very old HP Computers) (/forum-3.html)
+--- Forum: HP Prime (/forum-5.html)
+--- Thread: Python OOP broken? (/thread-17154.html)



Python OOP broken? - jfelten - 06-23-2021 08:51 PM

Whenever I try to call a class method, the interpreter sometimes doesn't recognize that the "self" parameter is implied. most of my tests worked fine, but one certain case gave me an error:

Code:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "main.py", line 5, in <module>
  File "game.py", line 20, in __init__
TypeError: initialize() takes 1 positional arguments but 0 were given

(In case you're wondering, I am trying to recreate the popular board game Risk.)

Here is my code so far:

main.py:
Code:
import player
import game
from hpprime import *

Game=game.RGame()

fillrect(0,0,0,320,240,0x90c0ff,0x90c0ff)
blit(0,0,0,2)

"""
for p in Game.players:
  p.initialize()
"""

game.py:
Code:
import player
from hpprime import *

class RGame():
  def __init__(self):
    eval('G2:=AFiles("board.png")')

    self.playerCount=3
    self.multiplayer=False
    startTroops=[40,35,30,25][self.playerCount-2]
    self.players=[]

    for i in range(self.playerCount):
      if self.multiplayer==True or self.playerCount==0:
        self.players.append(player.HumanPlayer)
      else:
        self.players.append(player.HumanPlayer)
      p=self.players[-1]
      p.troopsToDeploy=startTroops
      p.initialize()
      self.players[-1]=p

      print(str(p))

  def render(self):
    fillrect(0,0,0,320,240,0x90c0ff,0x90c0ff)
    blit(0,0,0,2)

player.py:
Code:

class Player():
  def __init__(self, id):
    self.id=None
    self.occTerritories=[]
    self.TroopsToDeploy=0

  def __str__(self):
    return "id: "+str(self.id)+"\nTroops to deploy: "+str(self.TroopsToDeploy)

  def placeTroops(self):
    pass

  def initialize(self):
    self.placeTroops()

class HumanPlayer(Player):
  def __init__(self):
    self.object_variable= 1

  def placeTroops(self):
    print("place your troops")

Is it a problem with my code, the interpreter, or both?


RE: Python OOP broken? - Albert Chan - 06-23-2021 09:20 PM

(06-23-2021 08:51 PM)jfelten Wrote:  self.players.append(player.HumanPlayer)

You might need to create a class instance:

self.players.append(player.HumanPlayer())