Reputation: 35
class Air:
def __init__(self,supplier,delivery,ensurance):
self.supplier = supplier
self.delivery = delivery
self.ensurance = ensurance
def rate_for_custom(self):
return (self.supplier + self.delivery + self.ensurance)
class Sea:
def __init__(self,supplier,delivery,ensurance,port_tax):
self.supplier = supplier
self.delivery = delivery
self.ensurance = ensurance
self.port_tax = port_tax
def rate_for_custom(self):
return (self.supplier + self.delivery + self.ensurance + self.port_tax)
so i'm trying to write a program that calculates the import taxes in israel.
There are two types: one in the sea and one in the air
they both share the same attributes except Sea needs to be calculated with another attribute.
I'm feeling like my code is not good(i'm new to pragramming started a week ago)
is it fine to use two classes in this case? if not what is the solution (by stil using OOP because I need to practice with it)
Upvotes: 0
Views: 91
Reputation: 128
As you want to learn OOP, then you can start to see the concept of inheritance. Here is an example:
# generic class
class Custom:
def __init__(self,*args):
# collect all given parameters:
self.args = args
def rate_for_custom(self):
# just sum all numbers in given parameter:
return sum(self.args)
class Sea(Custom):
def __init__(self,supplier=0,delivery=0,insurance=0, port_tax = 0):
# Call Custom class and provide all relevant parameters:
super().__init__(supplier, delivery, insurance, port_tax)
class Air(Custom):
def __init__(self,supplier=0, delivery=0, insurance=0):
# Call Custom class and provide all relevant parameters:
super().__init__(supplier, delivery, insurance )
print(Custom(100,50,25).rate_for_custom())
# 175
print(Air(supplier=100,delivery=50,insurance=25).rate_for_custom())
# 175
print(Sea(supplier=100,delivery=50,insurance=25,port_tax=25).rate_for_custom())
# 200
Custom
class is doing all the job, by summing all parameters it receives in init(). You can call this class providing the values to sum :Custom(100,50,25).rate_for_custom()
Two other classes Air
and Sea
are inheriting from the Custom
class and are just an interface. Using them allows you to use keyword arguments instead of simple arguments: Sea(supplier=100,delivery=50,insurance=25,port_tax=25)
which is more friendly.
Upvotes: 1
Reputation: 12927
You can move common parts to a common parent class:
class Transport:
def __init__(self,supplier,delivery,ensurance):
self.supplier = supplier
self.delivery = delivery
self.ensurance = ensurance
def rate_for_custom(self):
return (self.supplier + self.delivery + self.ensurance)
class Air(Transport):
pass
class Sea(Transport):
def __init__(self,supplier,delivery,ensurance,port_tax):
super().__init__(supplier, delivery, ensurance)
self.port_tax = port_tax
def rate_for_custom(self):
return super().rate_for_custom() + self.port_tax
Upvotes: 1