Home Why is a variable in __init__() method not defined in the subclass?
Reply: 1

Why is a variable in __init__() method not defined in the subclass?

Jacob.L
1#
Jacob.L Published in 2018-01-13 00:47:27Z

In subclass ComputerGame, Toy.__init__(self,n), n is undefined.

Why is it warning me that the variable n is undefined when I try to call the __init__() function in the base class? Simply put, why is Toy.__init__(self,n) not callable in the subclass? I have declared ComputerGame (Toy):. Why isn't it inheriting the method Toy.__init__(self,n)?

Should I declare the variable outside the class?

class Toy:
  def __init__(self,n):
    self.__ToyName = n
    self.__ToyID = ""
    self.__Price = 0.00
    self.__MinimumAge = 4

  def SetToyName(self,p):
    self.__ToyName = p
  def SetToyID(self,d):
    self.__ToyID = d
  def SetPrice(self,i):
    self.__Price = i
  def SetMinimumAge(self,i):
    self.__MinimumAge = i
  def GetToyName(self):
    return (self.__ToyName)
  def GetToyID(self):
    return (self.__ToyID)
  def GetPrice(self):
    return (self.__Price)
  def GetMinimumAge(self):
    return (self.__MinimumAge)


class ComputerGame(Toy):
  def __init__(self):
    Toy.__init__(self,n)
    self.__Catogory = ""
    self.__Console = ""

  def SetCatogory(self,c):
    self.__Catogory = c
  def SetConsole(self,c):
    self.__Console = c
  def GetCatogory(self):
    return (self.__Catogory)
  def GetConsole(self):
    return (self.__Console)
Prune
2#
Prune Reply to 2018-01-13 01:00:34Z

This is a scoping issue:

class ComputerGame(Toy):
  def __init__(self):
    Toy.__init__(self,n)

This is the first appearance of n. When you create a ComputerGame, your __init__ methods requires you (the calling program) to supply n as part of the creation. That's how you wrote the code.

The __init__ above assumes that n will appear magically from nowhere. I'm unclear what data flow you expect from this -- and so is the Python compiler. I don't know how to fix this for you, since you failed to supply a Minimal, complete, verifiable example. We should have at least one line of main code to create the object.

One strong possibility is fairly simple:

class ComputerGame(Toy):
  def __init__(self, n):
    Toy.__init__(self, n)

NewFPS = ComputerGame("Universal Uzi")

Does that clear it up?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.353855 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO