until_now = (today - self.pd).days ^^^^^^^ AttributeError: 'Medicine' object has no attribute 'pd'
时间: 2024-02-15 21:58:43 浏览: 14
根据提供的引用内容,可以看出这是两个不同的问题。第一个问题是关于Python中的AttributeError,第二个问题是关于Medicine对象的AttributeError。
针对第二个问题,根据错误提示,可以看出'Medicine'对象没有'pd'属性。这意味着在创建'Medicine'对象时,没有为其定义'pd'属性。因此,需要检查代码并确保在创建'Medicine'对象时定义了'pd'属性。
以下是一个可能的解决方案:
```python
class Medicine:
def __init__(self, name, pd):
self.name = name
self.pd = pd # 在这里定义'pd'属性
today = date.today()
pd = date(2021, 1, 1)
medicine = Medicine('Aspirin', pd)
until_now = (today - medicine.pd).days
print(until_now)
```
这里我们在'Medicine'类的构造函数中定义了'pd'属性,并在创建'Medicine'对象时为其赋值。这样,我们就可以在后面的代码中使用'medicine.pd'来获取'Medicine'对象的'pd'属性。
相关问题
self._name_scope = self.name.strip("_") AttributeError: 'property' object has no attribute 'strip
这个错误是因为你正在尝试对一个属性对象进行`strip`操作,而属性对象是不可直接进行字符串操作的。`strip()`方法是用于移除字符串两侧的空格符或指定字符。
如果你想对属性名进行去除下划线操作,你可以先将属性值获取到,然后再对其进行操作。例如:
```python
name = self.name
name_scope = name.strip("_")
```
或者,你可以直接在获取属性值时进行去除下划线操作:
```python
name_scope = self.name.strip("_")
```
请确保`self.name`是一个字符串类型才可以使用`strip`方法。如果不是字符串类型,你可以先将其转换为字符串类型再进行操作。
self.predict_y = self.reg.predict(_X) AttributeError: 'NoneType' object has no attribute 'predict'
This error message suggests that the object "self.reg" is of type "NoneType", which means it has no attribute called "predict". Therefore, when the code tries to call the "predict" method on "self.reg", it raises an AttributeError.
To fix this error, you need to make sure that "self.reg" is initialized properly and is not None. You can check if "self.reg" is None by adding a print statement before the line that raises the error:
```
print(self.reg) # add this line to check if self.reg is None
self.predict_y = self.reg.predict(_X)
```
If the output of the print statement is "None", then you need to initialize "self.reg" before calling the "predict" method. For example, if you are using scikit-learn's linear regression model, you can initialize "self.reg" as follows:
```
from sklearn.linear_model import LinearRegression
class MyModel:
def __init__(self):
self.reg = LinearRegression()
def fit(self, X, y):
self.reg.fit(X, y)
def predict(self, X):
_X = self._transform(X)
self.predict_y = self.reg.predict(_X)
return self.predict_y
```
This initializes "self.reg" to a new instance of the LinearRegression class, which has the "predict" method you need to call later.