你会如何使用不同的对象在python中编写自定义类?

时间:2015-06-03 11:34:33

标签: java python class

我正在尝试学习如何在python中编码,但在寻找在线创建自定义类的方法时遇到了麻烦。我用java编写了一个程序,我试图在python中转换它。我想我已经定制了班级(我不确定),而且我确实遇到了驱动程序问题。

我的自定义类(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

我的python驱动程序尝试

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()

我的java自定义类和驱动程序:

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 个答案:

答案 0 :(得分:3)

在Python中,没有public vs private的概念,一切都是public所以你不需要setter或getter。

您需要的是__init__函数,它类似于构造函数。您可以在此处初始化成员变量,以使它们不是静态的,并在您的类的所有实例之间共享。您还可以添加默认参数,以便您在实例化时传入任何,全部或没有任何参数。

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()

然后您可以创建此类的实例。再次注意,您可以直接访问没有setter或getter的成员,无论好坏;)

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

现在您可以在对象上调用print

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

最后,您接受用户输入的方式通常是input(尽管弄乱stdin并不一定是错误的)

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

答案 1 :(得分:1)

Python的另一个不错的功能是内置的@property装饰器, 这有助于从Java中取代setter和getter。 @property @property decorator允许您使用属性创建类的早期版本 属性(即self.tax)。如果以后有必要执行 计算属性或将其移动到计算属性, {{3}}属性允许透明地完成任何操作 代码取决于现有的实现。见下面的例子。

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

答案 2 :(得分:-1)

就像CoryKramer所说的那样,python并不鼓励使用私人员工,而且你不需要安装者和吸气剂。但如果你仍然想要,这可能会有所帮助:

writeRaster