-1

trying to understand classes and methods in Python 3.7. I keep running the code below, but keep getting this NameError, associated with the points variable I established in the initialize method of the Stats class. I believe the error is the result of some problem recognizing local/global variables, but can't put my finger on it. Does anyone have any ideas?

class Stats:
    def __init__(self, points, rebounds, assists, steals):
        self.points = points
        self.rebounds = rebounds
        self.assists = assists
        self.steals = steals

    def tripDub(self):
        if points >= 10 and rebounds >= 10 and assists >= 10 and steals >= 10:
            return "Yes!"
        else:
            return "Nope!"

s = Stats(30, 20, 9, 5)
print("Did he earn a Triple Double? Result:", s.tripDub())
Alec
  • 8,529
  • 8
  • 37
  • 63
nick_rinaldi
  • 641
  • 6
  • 17
  • 2
    In the tripDub() method you need to refer to class variables using self. e.g. `if self.points >= 10 and self.rebounds >= 10 and self.assists >= 10 and self.steals >= 10:` – Maximus Apr 22 '19 at 04:12
  • If any of the answers solved your question, it's good practice to upvote them and accept the best one. The latter also grants you a small rep bonus :) – Alec May 14 '19 at 22:08
  • Think carefully about the logic. Where the code says `self.points = points`, why does it not simply say `points=points`? What does the `self.` part mean? Do you see how this applies to the `tripDub` method as well? – Karl Knechtel Sep 05 '22 at 09:24

2 Answers2

4

You need self. before referencing instance variables:

class Stats:
    def __init__(self, points, rebounds, assists, steals):
        self.points = points
        self.rebounds = rebounds
        self.assists = assists
        self.steals = steals

    def tripDub(self):
        if self.points >= 10 and self.rebounds >= 10 and self.assists >= 10 and self.steals >= 10:
            return "Yes!"
        else:
            return "Nope!"


s = Stats(30, 20, 9, 5)
print("Did he earn a Triple Double? Result:", s.tripDub())
Alec
  • 8,529
  • 8
  • 37
  • 63
3

You need to reference points, rebounds, assists and steals using self in the tripDub function.

Example: self.points

JeremyFromEarth
  • 14,344
  • 4
  • 33
  • 47