现在我得到了一个更好看的新代码概述:
class innentemp:
import ipywidgets as widgets from ipywidgets import interact
import matplotlib.pyplot as plt
import numpy as np
it = widgets.IntSlider(min=20, max=30, value=1, description='Innentemp:')
nt = widgets.IntSlider(min=10, max=25, value=1, description='Nachttemp:')
applyButton = widgets.Button(
description='Update',
disabled=False,
button_style='',
tooltip='Suchen',
icon='check',
)
display(it, nt, applyButton)
def inside_temperature(self,it, nt):
temp_list = []
for i in range(8759):
avg_temp = 0.5*(it-nt)*math.sin(((2*math.pi)/24)*(i-6))+((it-nt)*0.5)+nt
temp_list.append(avg_temp)
return temp_list
def apply(self):
num_temp_list = innentemp.inside_temperature(self.it.value, self.nt.value)
plt.plot(np.arange(8759), num_temp_list, linewidth=0.1)
plt.show()
applyButton.on_click(apply)
And here is the Error:
AttributeError Traceback (most recent
call last)
<ipython-input-10-e523fe3d0dba> in apply(self)
26 def apply(self):
27
---> 28 num_temp_list =
innentemp.inside_temperature(self.it.value, self.nt.value)
29 plt.plot(np.arange(Integer(8759)), num_temp_list,
linewidth=RealNumber('0.1'))
30 plt.show()
AttributeError: 'Button' object has no attribute 'it'
我试着放一个“自我”。开始时两个滑块的前面(it,nt),但效果不佳。
回答1
这可能是因为在函数 apply
中,你这样做了
num_temp_list = innentemp.inside_temperature(self.it.value, self.nt.value)
您正试图从类 innentemp
调用 inside_temperature
,但您确实需要从 self
调用它。
你需要做
num_temp_list = self.inside_temperature(self.it.value, self.nt.value)
或者
num_temp_list = innentemp.inside_temperature(self, self.it.value, self.nt.value)
例如,如果您有一个类 Person
并且您尝试
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def printName(self):
print("Name:", self.name)
def printAge(self):
print("Age:", self.age)
def printData(self):
Person.printName() # Error: missing 1 required positional argument: 'self'
Person.printAge() # Error: missing 1 required positional argument: 'self'
john = Person("John", 20)
john.printData()
它不起作用,因为您需要从 self
调用,而不是 Person
。
所以这意味着这有效:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def printName(self):
print("Name:", self.name)
def printAge(self):
print("Age:", self.age)
def printData(self):
self.printName()
self.printAge()
john = Person("John", 20)
john.printData()
Name: John
Age: 20