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

Java 如何使用不同的对象在python中编写自定义类?,java,python,class,Java,Python,Class,我正在尝试学习如何用python编写代码,但在寻找在线创建自定义类的方法时遇到了困难。我用java编写了一个程序,我正在尝试用python进行转换。我想我有自定义类(我不确定),我肯定有麻烦的司机 我的自定义类(python): 我的python驱动程序尝试 import sys from CostCalculator import CostCalculator item = "" cost = 0.0 totalTip = 0.0 totalTax = 0.0 overallTotal =

我正在尝试学习如何用python编写代码,但在寻找在线创建自定义类的方法时遇到了困难。我用java编写了一个程序,我正在尝试用python进行转换。我想我有自定义类(我不确定),我肯定有麻烦的司机

我的自定义类(python):

我的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);
    }   
}

在Python中,没有
public
private
的概念,一切都是
public
,因此不需要setter或getter

您需要的是
\uuu init\uu
函数,它类似于构造函数。您可以在这里初始化成员变量,使它们不是静态的,并在类的所有实例之间共享。您还可以添加默认参数,以便在实例化时向类传递任何、所有或无参数

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

现在您可以在对象上调用
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
并不一定是错误的)


正如CoryKramer所说,python不鼓励使用私有员工,也不需要setter和getter。但如果您仍然想加入,这可能会有所帮助:

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

Python的另一个很好的特性是内置的装饰器, 这有助于替换Java中的setter和getter。这个 decorator允许您使用属性创建类的早期版本 属性(即,
self.tax
)。如果以后需要执行 计算属性或将其移动到计算属性时 属性允许对任何用户透明地执行此操作 依赖于现有实现的代码。见下面的例子

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

为便于将来参考,请注意,在3.x之前的Python版本上,您应该更喜欢
raw_input()
而不是
input()
--
input()
评估输入的文本并显示安全风险--例如,如果我想将税设置为费率x costOfItem而不是静态值,该怎么办?我会将其保留在初始化方法中吗?@JamieVu在这种情况下,我甚至不会将
tax
tip
作为成员变量,因为它们依赖于
成本。我会制作助手函数
get\u tax
get\u tip
,它们可以计算这个。请参阅我的编辑以获取示例这将是一个问题<代码>\u项
等不应在类定义本身中设置,否则它们将在
成本计算器
的所有实例中共享。如果您创建了该类的两个实例,更改其中一个中的
\uuuu item
将影响另一个。此外,根据PEP8,成员变量名称不应以双下划线开头,这是为某些函数保留的,它们将被损坏。我知道双下划线,只需重写原始类,如果@Jamie Vu想要像现在这样拥有它。但是我不同意影响
\uuuu项目
关于影响
\uuu项目
,这是一个坏例子,因为它们的成员是不可变的
str
int
,但是如果它们有可变的成员,比如
列表
,这确实会产生不期望的行为。完全同意。但这不影响它在这里,所以我把它留下了。
>>> tax = input('how much does this thing cost? ')
how much does this thing cost? 15.0
>>> tax
'15.0'
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])
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