How could you write your own class in python using different objects?

I am trying to learn how to write python code but I am having trouble finding ways to create custom classes on the web. I have written a program in java and I am trying to convert it to python. I think I have my own class down (I'm not sure) and I am definitely having driver issues.

my custom class (python):

class CostCalculator:
    __item = ""
    __costOfItem = 0.0
    __tax = 0.0
    __tip = 0.0

    def set_item(self, item):
        self.__item = item
    def get_name(self):
        return self.__item

    def set_costOfItem(self, costOfItem):
        self.__costOfItem = costOfItem
    def get_costOfItem(self):
        return self.__costOfItem

    def get_tax(self):
        __tax = self.__costOfItem * .0875
        return self.__tax

    def get_tip(self):
        __tip = self.__costOfItem * .15
        return self.__tip

      

My python driver attempt

import sys
from CostCalculator import CostCalculator

item = ""
cost = 0.0
totalTip = 0.0
totalTax = 0.0
overallTotal = 0.0
subtotal = 0.0

print("Enter the name of 3 items and their respective costs to get the total value of your meal")
print ("\n Enter the name of your first item: ")
item = sys.stdin.readline()
print("How much is " + item + "?")
cost = sys.stdin.readLine()

      

My custom java class and driver:

public class TotalCost
{
   String item = " ";
   double costOfItem = 0;
   double tax = 0;
   double tip = 0;

   public void setItem ( String i )
   {
       item = i;
    }

   public String getItem()
   {
       return item;
    }

   public void setCostOfItem ( double c )
   {
       costOfItem = c;
    }

   public double getCostOfItem ()
   {
       return costOfItem;
    }

   public double getTax ()
   {
       double tax = costOfItem * .0875;
       return tax;
    }

   public double getTip()
   {
      double tip = costOfItem * .15;
      return tip;
    }

   public String toString()
   {
      String str;
        str = "\nMeal: " + getItem() +
        "\nCost of " + getItem() + ": " + getCostOfItem() +
        "\nTax of " + getItem() + ": " + getTax() +
        "\nTip of " + getItem() + ": " + getTip();
      return str;

    }

}

import java.util.Scanner;
public class Driver
{
    public static void main (String args[])
    {
        Scanner input = new Scanner (System.in);

        String item ;
        double cost ;
        double totalTip = 0;
        double totalTax = 0;
        double OverallTotal = 0;
        double subtotal;
        TotalCost a = new TotalCost ();
        TotalCost b = new TotalCost ();
        TotalCost c = new TotalCost ();

        System.out.println("Enter the name of 3 items and their respective costs to get the total value of your meal");
        System.out.println("Enter the name of your first item: ");
        item = input.nextLine();
        a.setItem ( item );
        System.out.println("How much is " + a.getItem() + "?" );
        cost = input.nextDouble();
        a.setCostOfItem (cost);

        input.nextLine();

        System.out.println("Enter the name of your second item: ");
        item = input.nextLine();
        b.setItem (item);
        System.out.println("How much is a " + b.getItem() + "?");
        cost = input.nextDouble();
        b.setCostOfItem (cost);

        input.nextLine();

        System.out.println("Enter the name of your third item: ");
        item = input.nextLine();
        c.setItem (item);
        System.out.println("How much is a " +c.getItem() + "?" );
        cost = input.nextDouble();
        c.setCostOfItem(cost);

        System.out.println(a + "\n" + b + "\n" + c);
        subtotal = a.getCostOfItem() + b.getCostOfItem() + c.getCostOfItem();
        totalTip = a.getTip() + b.getTip() + c.getTip();
        totalTax = a.getTax() + b.getTax() + c.getTax();
        OverallTotal = subtotal + totalTip + totalTax;

        System.out.println("\n\tSubtotal: $" + subtotal);
        System.out.println("\tTax: $" + totalTax);
        System.out.println("\tTip: $" + totalTip);
        System.out.println("\tMeal Total: $" + OverallTotal);
    }   
}

      

+3


source to share


3 answers


There is no concept of public

vs in Python private

, all of this public

, so you don't need setters or getters.

You need a function __init__

that is similar to a constructor. You can initialize member variables here so that they are not static and propagated to all instances of your class. You can also add default arguments so that many of you pass any, all, or none of the class arguments when instantiating.

class CostCalculator:
    def __init__(self, item = "", cost = 0.0):
        self.item = item
        self.cost = cost

    def __str__(self):
        return 'Meal: {item}\nCost of {item}: {cost}\nTax of {item}: {tax}\nTip of {item}: {tip}'.format(item = self.item, cost = self.cost, tax = self.calc_tax(), tip = self.calc_tip())

    def calc_tax(self):
        return self.cost * 0.0875

    def calc_tip(self):
        return self.cost * 0.15

    def calc_total(self):
        return self.cost + self.calc_tax() + self.calc_tip()

      

Then you can instantiate this class. Note again that you can access members directly without setters or getters, for better or worse;)

>>> c = CostCalculator('cheese', 1.0)
>>> c.item
'cheese'
>>> c.calc_tip()
0.15

      



Now you can call print

on your object

>>> c = CostCalculator('cheese', 1.0)
>>> print(c)
Meal: cheese
Cost of cheese: 1.0
Tax of cheese: 0.085
Tip of cheese: 0.15

      

Finally, the way that you accept input from the user is usually through input

(although the mess with using is stdin

n't necessarily wrong)

>>> tax = input('how much does this thing cost? ')
how much does this thing cost? 15.0
>>> tax
'15.0'

      

+3


source


Another nice feature of Python is the built-in decoder @property

, which helps replace setters and getters with Java. @property

The decorator allows you to create early versions of a class using the attributes property (i.e. self.tax

). If you later need to perform calculations on the attribute or move it to a calculated attribute, @property

allows you to do this transparently for any code that depends on the existing implementation. See example below.



TAX_RATE = 0.0875
TIP_RATE = 0.15

class CostCalculator(object):
    def __init__(self, item='', cost=0):
        self.item = item
        self.cost = cost


    @property
    def tax(self):
        """Tax amount for item."""

        return self.cost * TAX_RATE


    @property
    def tip(self):
        """Tip amount for item."""

        return self.cost * TIP_RATE



if __name__ == '__main__':
    item = CostCalculator('Steak Dinner', 21.50)
    assert item.tax == 1.8812499999999999
    assert item.tip == 3.225

      

+1


source


It looks like CoryKramer said that python doesn't encourage the use of personal staff, and you don't need setters and getters. But if you still want, this might help:

class CostCalculator:
    __item = ""
    __cost_of_item = 0.0
    __tax = 0.0
    __tip = 0.0

    def set_item(self, item):
        self.__item = item

    def get_name(self):
        return self.__item

    def set_cost_of_item(self, cost_of_item):
        self.__cost_of_item = float(cost_of_item)

    def get_cost_of_item(self):
        return self.__cost_of_item

    def get_tax(self):
        self.__tax = self.__cost_of_item * 0.0875
        return self.__tax

    def get_tip(self):
        self.__tip = self.__cost_of_item * 0.15
        return self.__tip


item = ""
cost = 0.0
totalTip = 0.0
totalTax = 0.0
overallTotal = 0.0
subtotal = 0.0

print("Enter the name of 3 items and their respective costs to get the total vaalue of your meal")

ls = [CostCalculator(), CostCalculator(), CostCalculator()]

for entry in ls:
    print "Enter the name of your item:"
    item = raw_input()
    entry.set_item(item)
    print("How much is " + entry.get_name() + "?")
    cost = raw_input()
    entry.set_cost_of_item(cost)

subtotal = sum([x.get_cost_of_item() for x in ls])
totalTip = sum([x.get_tip() for x in ls])
totalTax = sum([x.get_tax() for x in ls])

      

-1


source







All Articles