简体   繁体   中英

Why does it keep showing Python 3 Code Error Class Not Defined but it was defined?

I get the following error message:

Traceback (most recent call last):
  File "main.py", line 13, in <module>
    class Archer(User):
  File "main.py", line 22, in Archer
    archer1 = Archer('Joie', 100)
NameError: name 'Archer' is not defined

from this code:

class User():
      def sign_in(self):
        print('logged in')
    
    class Wizard(User):
      def __init__(self, name, power):
        self.name = name 
        self.power = power
    
      def attack(self):
        print(f'attacking with power of {self.power}')
    
    class Archer(User):
      def __init__(self, name, num_arrows):
        self.name = name 
        self.num_arrows = num_arrows
    
      def attack(self):
        print(f'attacking with arrows: arrows left- {self.num_arrows}')
    
      wizard1 = Wizard('John', 50)
      archer1 = Archer('Joie', 100)
      wizard1.attack()
      archer1.attack()

Why is the Archer class "not defined" at this point?

Instead of indenting your last four lines you should have them like so:

class Archer(User):
  def __init__(self, name, num_arrows):
    self.name = name 
    self.num_arrows = num_arrows

  def attack(self):
    print(f'attacking with arrows: arrows left- {self.num_arrows}')


wizard1 = Wizard('John', 50)
archer1 = Archer('Joie', 100)
wizard1.attack()
archer1.attack()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM