I am having a very simple code of python, wherein I am creating an object array in the constructor, But whenever I try calling a display function to see all the objects in the Object Array, it returns this NoneType exception.
Class called Toy is the actual object class, which is shown below:
class Toy:
__name=None
__cost=None
def __init__(self,name,cost):
self.__name=name
self.__cost=cost
def get_Name(self):
return self.__name
def get_Cost(self):
return self.__cost
def print_Toy(self):
print(" Name of the toy: ",self.__name)
print(" Cost of the toy: ",self.__cost)
The below-shown class Toy_Bag contains the object array, which I am initializing in the constructor.
from Toy import Toy
class Toy_Bag:
__toys=[None]
def __init__(self, no_of_toys):
self.__create_Toy_bag(no_of_toys)
def __create_Toy_bag(self, no_of_toys):
name,cost= None,0
for toy in range(0, no_of_toys):
print("\n Enter the name of the toy: ",end="")
name=input()
print("\n Enter the cost of the toy: ",end="")
cost=int(input())
toy=Toy(name,cost)
self.__toys.append(toy)
self.print_Toy_Bag()
def print_Toy_Bag(self):
for toy in self.__toys:
toy.print_Toy()
Traceback (most recent call last):
File "Main.py", line 9, in <module>
toy_bag=Toy_Bag(3)
File "C:\Users\SONY\Desktop\Python Scripts\Tools\Toy_Bag.py", line 8, in __init__
self.__create_Toy_bag(no_of_toys)
File "C:\Users\SONY\Desktop\Python Scripts\Tools\Toy_Bag.py", line 19, in __create_Toy_bag
self.print_Toy_Bag()
File "C:\Users\SONY\Desktop\Python Scripts\Tools\Toy_Bag.py", line 23, in print_Toy_Bag
toy.print_Toy()
AttributeError: 'NoneType' object has no attribute 'print_Toy'
C:\Users\SONY\Desktop\Python Scripts\Tools>
Any help is highly appreciated.