为对象创建方法

2024-05-16 05:46:01 发布

您现在位置:Python中文网/ 问答频道 /正文

创建表示存储的对象。让初始化方法获取商店的平方英尺。创建一个可以计算商店电气成本的方法

class Store:
    DOLLARS_PER_KWH = 0.15
    KWH_PER_SQUARE_FOOTAGE_PER_HOUR = 0.19

    def __init__(self): 
        self.square_footage = square_footage

    def cost(self, DOLLARS_PER_KWH, KWH_PER_SQUARE_FOOTAGE_PER_HOUR):
        self.electrical_costs = self * DOLLARS_PER_KWH * KWH_PER_SQUARE_FOOTAGE_PER_HOUR
        print(f' Electrical costs are {self.electrical_costs} dollars.')

我在init调用中收到一个类型错误,以及一个名称错误和开销,这里有什么问题?请帮助编辑我的代码


Tags: 方法selfinitdefelectrical商店kwhsquare
2条回答
 class Store:
        DOLLARS_PER_KWH = 0.15
        KWH_PER_SQUARE_FOOTAGE_PER_HOUR = 0.19

        def __init__(self,square_footage): 
            self.square_footage = square_footage
            Store.DOLLARS_PER_KWH
            Store.KWH_PER_SQUARE_FOOTAGE_PER_HOUR

        def cost(self):
            self.electrical_costs = self.square_footage *Store.DOLLARS_PER_KWH *Store.KWH_PER_SQUARE_FOOTAGE_PER_HOUR
            print ("Electrical costs are $%.2f." % (self.electrical_costs))

    emp1 = Store(10)       
    emp1.cost()      

enter image description here

A few pointers

  1. square_footage未在__init__内定义,您可能想将其作为参数发送

  2. DOLLARS_PER_KWHKWH_PER_SQUARE_FOOTAGE_PER_HOUR作为参数发送给cost很可能不是您想要的,因为它们已经在类中定义了

  3. self *部分错误。您没有重载*,因此不能将Store对象与其他对象相乘

相关问题 更多 >