Hi All,
I am new to programming & trying to learn python.
I have created Product class(as Parent) & Inventory (as child) class. How can i use attributes declared in product class in inventory class. In the below example i want to use Product attribute 'pcost' in inventory class.
In Cost function i want to do pcost * pnbr.
Please help.
class Product():
def __init__(self,pname,pid,pcost):
self.pname = pname
self.pid=pid
self.pcost=pcost
class Inventory(Product):
def __init__(self,pnbr,products):
self.pnbr=pnbr
def cost(self):
self.cost=self.pcost*self.pnbr
Pro1=Product('Cookie','01',5)
Pro2=Product('Milk','02',3)
Hi All,
I am new to programming & trying to learn python.
I have created Product class(as Parent) & Inventory (as child) class. How can i use attributes declared in product class in inventory class. In the below example i want to use Product attribute 'pcost' in inventory class.
In Cost function i want to do pcost * pnbr.
class Product():
def __init__(self,pname,pid,pcost):
self.pname = pname
self.pid=pid
self.pcost=pcost
class Inventory(Product):
def __init__(self,pnbr,products):
Product.__init__(self,pname,pid,pcost)
self.pnbr=pnbr
def cost(self):
self.cost=self.pcost*self.pnbr
1. Init product need variables define.
class Inventory(Product):
def __init__(self, pnbr, products)
Product.__init__(self, "product name", 1, 20)
2. if you want a list of products do not inherit products
class Inventory:
def __init__(self, pnbr, products)
self.pnbr = pnbr
self.products = products
def cost(self, product_index):
return self.products[product_index].pcost * self.pnbr
(Nov-16-2017, 03:56 PM)Windspar Wrote: [ -> ]1. Init product need variables define.
The variables will be defined when make instance of the class.
(Nov-16-2017, 03:22 PM)Harry_Potter Wrote: [ -> ]In the below example i want to use Product attribute 'pcost' in inventory class. In Cost function i want to do pcost * pnbr.
class Product(object):
def __init__(self, pname, pid, pcost):
self.pname = pname
self.pid = pid
self.pcost = pcost
class Inventory(Product):
def __init__(self, pname, pid, pcost, pnbr, products):
Product.__init__(self, pname, pid, pcost)
self.pnbr = pnbr
self.products = products
def cost(self):
self.cost = self.pcost * self.pnbr
Use:
>>> obj = Inventory('Apple', 100, 20, 15, 'foo')
>>> obj.cost()
300
>>> obj.pcost
20
>>> obj.pnbr
15
Python 3 with
super()
.
class Product:
def __init__(self, pname, pid, pcost):
self.pname = pname
self.pid = pid
self.pcost = pcost
class Inventory(Product):
def __init__(self, pname, pid, pcost, pnbr, products):
super().__init__(pname, pid, pcost)
self.pnbr = pnbr
self.products = products
def cost(self):
self.cost = self.pcost * self.pnbr
return self.cost