0

I am writing a code in pythony, where I want my ball to move on a graph, and save the positions in a list (posx and posy) I made a ball class, but when I call the constructor, I get this error message: 'Ball' object has no attribute 'posx'. This is my code:

class Ball:
    def __init__(self,xvelocity=1, yvelocity=1, inx=1,iny=5, posx=[],posy=[]):
        self.xvelocity=xvelocity
        self.yvelocity=yvelocity
        #giving velocity
        self.inx=inx
        self.iny=iny
        #defining starting position
        self.posx[0]=self.inx
        self.posy[0]=self.iny

        


ball=Ball()

Do you know why this happens? Thank you for your help.

Bennett567
  • 535
  • 1
  • 3
  • 18
  • 3
    When you try `self.posx[0]=self.inx` `self.posx` is not defined. Same for `self.posy`. Finally - look at https://stackoverflow.com/q/1132941/4046632 to prevent the biggest issue in your code - mutable default arguments – buran Nov 11 '20 at 15:25
  • If you want to pass `posx` and `posy` as arguments and assuming you fix the error, do you really want to overwrite the element with index 0? Maybe you don't need `posx` and `posy` as parameters in your `__init__` method? – buran Nov 11 '20 at 15:28
  • Perhaps the OP wants to add the element to the beginning of the list but not overwrite what is already at `[0]`? If so they can use insert: `posx.insert(0, inx)`, then just set `self.posx = posx`. Or even cleaner: `self.posx = [inx] + posx`. [example](https://repl.it/@marsnebulasoup/SteelblueVillainousProgrammers#main.py) – marsnebulasoup Nov 11 '20 at 15:34
  • I want to add inx and iny as the first element in my list, and later on in the code, expand the posx and posy list. Thank you for your help – Bennett567 Nov 11 '20 at 16:46

1 Answers1

0

You have to define the attributes posx and posy as lists first. The next question would be if you actually want the position lists passed as argument.

    self.posx = [self.inx]
    self.posy = [self.iny]
hasleron
  • 499
  • 3
  • 10
  • 1
    Note that OP wants to pass posx and posy as arguments. – buran Nov 11 '20 at 15:25
  • That's possible, although not clear as you pointed out. Let's see if OP clarifies their intentions. – hasleron Nov 11 '20 at 15:33
  • The OP appears to be confused as to how the arguments differ from class attributes; `posx` and `posy` almost certainly are *not* needed as arguments. – chepner Nov 11 '20 at 15:39