Reputation: 65
guys don't know why getting name error for already defined object,trying to created a text based black jack game but getting error for already defined list(person and dealer ),when i try to run startGame function(actually this function give two random cards to both dealer and person and add both those value separately)
input
def rand():
king=10
jack=10
queen=10
one=2
two=3
three=4
four=5
five=6
six=7
seven=8
eight=9
nine=10
import random
return random.choice([king,queen,jack,one,two,three,four,five,six,seven,eight,nine,])
class black():
person=[]
dealer=[]
def __init__(self,rando):
self.rando=rando
def StartingGame(self):
import math
person.append(rand())
person.append(rand())
dealer.append(rand())
dealer.append(rand())
return math.fsum(person),math.fsum(dealer)
output
tt=black(rand())
tt.StartingGame()
NameError Traceback (most recent call last)
<ipython-input-4-adf1a6aa555c> in <module>
----> 1 tt.StartingGame()
<ipython-input-1-ad7bd57d22e4> in StartingGame(self)
26 import math
27
---> 28 person.append(rand())
29 person.append(rand())
30 dealer.append(rand())
NameError: name 'person' is not defined
Upvotes: 0
Views: 124
Reputation: 23
The problem is you are calling function local variable person
but not black
class property. dealer
variable also give you same error in the StartingGame
function. If you want to call class property person
and dealer
you have to call it by function self
variable. Example self.person
self.dealer
.
Upvotes: 0
Reputation: 13079
There are two problems with the class as it stands in the question.
One is a simple issue of scope: class is not a scope which is searched when resolving names, so you need to use self.person
and not just person
.
The other issue is that you are using mutable objects (here lists) as class variables. You will find if you do that that other instances of the same class will share the same objects for these variables, which is probably not what you want. Instead, use instance variables, initialising them inside __init__
:
import math
# ...
class Black():
def __init__(self, rando):
self.rando = rando
self.person = []
self.dealer = []
def starting_game(self):
self.person.append(rand())
self.person.append(rand())
self.dealer.append(rand())
self.dealer.append(rand())
return math.fsum(person), math.fsum(dealer)
Note also other corrections:
Upvotes: 0
Reputation: 32163
You should use self.person
, because class
scope is not included in LEGB-rule.
Upvotes: 1