Python AttributeError:type object';汽车&x27;没有属性';速度';
我用对象Car调用Car类时收到错误消息Python AttributeError:type object';汽车&x27;没有属性';速度';,python,Python,我用对象Car调用Car类时收到错误消息 class Car: def __init__(self, speed, unit): self.speed = speed self.unit = unit def __new__(self, speed, unit): str = "Car with the maximum speed of {} {}".format(self.speed, self.unit) return str 新建是创建
class Car:
def __init__(self, speed, unit):
self.speed = speed
self.unit = unit
def __new__(self, speed, unit):
str = "Car with the maximum speed of {} {}".format(self.speed, self.unit)
return str
新建是创建实例的第一步它被称为first,负责返回类的新实例 相反,init不返回任何内容;它只负责在创建实例后初始化实例
class Car:
# def __init__(self, speed, unit):
# self.speed = speed
# self.unit = unit
def __new__(self, speed, unit):
self.speed = speed
self.unit = unit
str = "Car with the maximum speed of {} {}".format(self.speed, self.unit)
return str
a = Car(10, 2)
print(a)
一般来说,您不需要重写new,除非您正在对不可变类型(如str、int、unicode或tuple)进行子类化
另一种方式
class Car:
def __init__(self, speed, unit):
self.speed = speed
self.unit = unit
def __str__(self):
str = "Car with the maximum speed of {} {}".format(self.speed, self.unit)
return str
a = Car(10, 2)
print(a)
固定压痕,并使用方法
speed\u check()
和单个构造函数:
class Car:
def __init__(self, speed, unit):
self.speed = speed
self.unit = unit
def speed_check(self):
return "Car with the maximum speed of {} and the unit {}".format(self.speed, self.unit)
CarObj = Car(120, 10)
result = CarObj.speed_check()
print(result)
输出:
Car with the maximum speed of 120 and the unit 10
您正在使用
\uuuuu new\uuuuu
,我不知道为什么。您可以改为使用此选项:
class Car:
def __init__(self, speed, unit):
self.speed = speed
self.unit = unit
def new(self):
str = "Car with the maximum speed of {} {}".format(self.speed, self.unit)
return str
我想通过调用object@VivekGautam我很高兴它有帮助,如果您的问题得到解决,请将其标记为答案!
Car with the maximum speed of 120 and the unit 10
class Car:
def __init__(self, speed, unit):
self.speed = speed
self.unit = unit
def new(self):
str = "Car with the maximum speed of {} {}".format(self.speed, self.unit)
return str