简体   繁体   English

使用 class 内部的函数时出错。 我无法将 function 分配给新的 class 方法

[英]Error using functions inside of a class. I can't assign a function to a new class method

I'm trying to create a new method for my class 'Cloth', the method is called 'max_temp' and, to ease the task, i created the following function (max_temperature) to keep a cleaner code in the init part.我正在尝试为我的 class 'Cloth' 创建一个新方法,该方法称为 'max_temp',为了简化任务,我创建了以下 function (max_temperature) 以在init部分保持更清晰的代码。 I can't understand why it doesn't calculate the 'max_temp' method tho我不明白为什么它不计算'max_temp'方法

class cloth():
    def __init__(self, category, name):
        self.category = category
        self.name = name
        self.max_temp = max_temperature(category)

    def max_temperature(category):
        temps = {
            'sweater' : 24,
            'shirt' : 45}
        return temps[category]

x = cloth('sweater', 'cam_eco')

print(x.max_temp)
>>> print(x.max_temp)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

If you define a method inside a class then it needs to be either passed self as the first argument, or define it as a staticmethod or classmethod .如果您在 class 中定义方法,则需要将self作为第一个参数传递,或者将其定义为staticmethodclassmethod Otherwise you need to define it outside the class.否则你需要在 class 之外定义它。

So max_temperature needs to declared as one of:所以max_temperature需要声明为以下之一:

@staticmethod # or @classmethod (Ill leave looking up the difference to you)
def max_temperature(category):
    ....

or或者

def max_temperature(self, category):
    ....

or define it outside the class.或在 class 之外定义它。

If you define it inside the class then you should call it via self (or the class name if its a classmethod):如果你在 class 中定义它,那么你应该通过self调用它(或者 class 名称,如果它是一个类方法):

class cloth: # Note I removed the () from the class
    def __init__(self, category, name):
        self.category = category
        self.name = name
        self.max_temp = self.max_temperature(category)
...

So overall:所以总的来说:

class cloth:
    def __init__(self, category, name):
        self.category = category
        self.name = name
        self.max_temp = self.max_temperature(category)

    @staticmethod
    def max_temperature(category): # TODO you should add error handling to this method
        temps = {
            'sweater' : 24,
            'shirt' : 45
        }
        return temps[category]

x = cloth('sweater', 'cam_eco')
print(x.max_temp) # 24

The question has been already answered by Austin, but If you are not ok with static concept yet, then your code will look like奥斯汀已经回答了这个问题,但是如果您对 static 概念还不太满意,那么您的代码将如下所示

    class cloth():
        def __init__(self, category, name):
            self.category = category
            self.name = name
            self.max_temp = self.max_temperature(category)

        def max_temperature(self,category):
            temps = {'sweater' : 24,'shirt' : 45}

            return temps[category]

    x = cloth('sweater', 'cam_eco')

    print(x.max_temp)

Have you tried using self.category as the argument in the max_temperature function?您是否尝试过使用 self.category 作为 max_temperature function 中的参数?

class cloth():
    def __init__(self, category, name):
        self.category = category
        self.name = name
        self.max_temp = max_temperature(category)

    def max_temperature(self, self.category):
        temps = {
            'sweater' : 24,
            'shirt' : 45}
        return temps[category]

x = cloth('sweater', 'cam_eco')

print(x.max_temp)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我收到类中定义的属性的属性错误。 我怎样才能解决这个问题? - I am getting an attribute error for an attribute defined inside the class. How can I fix this? 为什么我不能在班级中访问变量。 蟒蛇 - why can't I access the variable in my class. python 我在简单的 class 中看不到组合框。如何解决? - I can't see comboboxes in a simple class. How to solve? 如何在新类中继承所有sqlalchemy函数? - How can I inherit all sqlalchemy functions inside a new class? 在类方法中使用__builtin__函数的属性错误 - Attribute error using __builtin__ functions inside class method 尝试在一个类中使用多个函数时发生Python错误。 Tkinter的 - Python error when trying to use multiple functions in a class. Tkinter 我正在重写HTMLCalendar类中的方法。 但它给了我一个错误。 我该如何正确地继承这个? - I am overriding a method in HTMLCalendar class. But it gives me an error. How do I inherit this correctly? 为什么我不能在 class 体内调用 static 方法? - Why can't I invoke a static method inside the class body? 通过创建一个实例作为属性,我可以从 Electric Car class 访问 Car class 的任何方法。 谁能深入解释这些? - By creating an instance as an attribute, I can access to any method of the Car class from Electric Car class. Can anyone explain these in depth? 我无法计算上课的年龄。 有人可以检查一下吗? - I can't calculate the age in a class. Could someone please check?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM