```python
class Peason():
def __init__(self, name):
self.name = name
def go_to(self, place, vehice):
self.place = place
self.vehice = vehice
vehice.run()
print(f"{self.name}驾驶{self.vehice.brand}{self.vehice}去{self.place}")
class Car():
def __init__(self, brand):
self.brand = brand
def run(self):
print("行驶")
lz = Peason("老张")
car = Car("奔驰")
lz.go_to("东北", "车")
######
```python
Traceback (most recent call last):
File "/home/tarena/month01/day10/exercise2.py", line 55, in
lz.go_to("东北", "车")
File "/home/tarena/month01/day10/exercise2.py", line 41, in go_to
vehice.run()
AttributeError: 'str' object has no attribute 'run'
######正确赋值,并且能输出我想要的语句
class Peason():
def __init__(self, name):
self.name = name
self.car=Car('奔驰')
def go_to(self, place, vehice):
self.place = place
self.vehice = vehice
self.car.run()
print(f"{self.name}驾驶{self.car.brand}{self.vehice}去{self.place}")
class Car():
def __init__(self, brand):
self.brand = brand
def run(self):
print("行驶")
lz = Peason("老张")
lz.go_to("东北", "车")
在你调用 lz.go_to("东北", "车") 时,你将字符串 "车" 作为 vehicle 参数传入了 go_to 方法。但是在 go_to 方法内部,你使用了 vehicle.run() 方法,这意味着你希望 vehicle 是一个有 run 方法的对象。然而,你传入的是一个字符串,字符串并没有 run 方法,因此会抛出异常。
要解决这个问题,你需要确保传入的 vehicle 参数是一个有 run 方法的对象,例如你创建的 Car 对象。修改代码如下:
lz = Peason("老张")
car = Car("奔驰")
lz.go_to("东北", car)
在调用lz.go_to方法时,传入的vehicle参数应该是一个Car类型的对象,但是直接传入了一个字符串"车"。这导致了AttributeError的发生,因为字符串对象没有run方法。
正确的做法应该是:
lz = Peason("老张")
car = Car("奔驰")
lz.go_to("东北", car)
这样就能正确的调用Peason类的go_to方法,并且能够正常地输出想要的语句了。
同时,在Peason类的go_to方法中,也可以将vehicle参数改为self.vehicle,这样就可以避免在方法内部使用局部变量vehicle了。
class Peason():
def init(self, name):
self.name = name
def go_to(self, place, vehice):
self.place = place
self.vehicle = vehice
self.vehicle.run()
print(f"{self.name}驾驶{self.vehicle.brand}{self.vehicle}去{self.place}")
仅供参考,望采纳,谢谢。
AttributeError: 'str' object has no attribute 'run'
报错含义:
AttributeError:“str”对象没有属性“run”
你对比下这个实例的跨类调用方法,
class Person:
def __init__(self, name=None):
self.name = name
def go_to(self,car):
print('开车')
car.move()
class Car:
def move(self):
print('去东北')
lz = Person('lz')
car=Car()
lz.go_to(car)
# 开车
# 去东北
出现问题的原因是你对字符串进行了属性的调用,而实际上是需要对相应的类进行初始化,为了能够进行跨类的调用,需要在类的函数中进行被调用类的初始化,具体的代码修改如下:
class Car:
def __init__(self, brand):
self.brand = brand
def run(self):
print("行驶")
class Person(Car):
def __init__(self, name):
self.place = None
self.vehicle = None
self.name = name
def go_to(self, place, vehicle, brand):
self.place = place
self.vehicle = vehicle
a = Car(brand)
a.run()
print(f"{self.name}驾驶{brand}{self.vehicle}去{self.place}")
name = "老张"
car_name = "奔驰"
lz = Person(name)
lz.go_to("东北", "车", car_name)
运行的结果为:
如果问题得到解决的话请点 采纳~~