2

So I am new to class in Python but not new to classes in general. I want to generate a new number in the object I create, and constantly change it.

So I did

    class ArmedBandit1:
        num = 0
        def spin():
            num = random(10)
    
    a1 = ArmedBandit1()
    
    a1.spin()
    print(a1.num)

Now I get an error

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    a1.spin()
TypeError: spin() takes 0 positional arguments but 1 was given

But I didn't give it any arguments, and if I try to remove the "()" it ignores the method.

Gex
  • 41
  • 5

4 Answers4

2

Define with self as first parameter! Define init and assign property! (To get random number in a range use random.randrange(10))

import random
class ArmedBandit1:
  def __init__(self):
    self.num = 0
  def spin(self):
    self.num = random.randrange(10)
  
    
a1 = ArmedBandit1()
a1.spin()
print(a1.num)

basics of python classes

Wasif
  • 14,755
  • 3
  • 14
  • 34
1

As @Mike67 suggested in the comments, you need to include the parameter self to have the method work for a particular instance of the class.

inavda
  • 333
  • 5
  • 15
1

In order for the object to assign a variable to it, you must create a init() function. You must also use the self keyword to refer to the object that you're creating. Here's an example with your code:

import random

class ArmedBandit1:
    def __init__(self):
        self.num = 0

    def spin(self):
        self.num = random.randrange(10)

a1 = ArmedBandit1()

a1.spin()
print(a1.num)
BWallDev
  • 345
  • 3
  • 13
1

Fixed Code!

import random
class ArmedBandit1:
    def spin(self):
        return random.randrange(10)

a1 = ArmedBandit1()

print(a1.spin())

Thank you to the help above!!

Gex
  • 41
  • 5