如何将其中一个属性的类型更改为 int?
How do I change one of my attributes' type to an int?
为了了解一些背景信息,我试图让自己熟悉对象、类 和 Python 上的属性。
class Plane:
def __init__(self,ModelName,brand,capacity):
self.ModelName = ModelName
self.brand = brand
self.capacity = capacity
def intro_plane(self):
print(
"The name of the plane is " + self.ModelName +
". It was released by " + self.brand +
". It has a capacity of " + self.capacity
)
P1 = Plane("B737", "Boeing", 155)
P1.intro_plane()
我 运行 我在 VsCode 上的代码,这是结果:
TypeError: can only concatenate str (not "int") to str
capacity
是 int
,不是 string
。因此,当您添加到 print
函数时,您需要更改它的类型。
". It has a capacity of " + str(self.capacity)
如错误所述:
TypeError: can only concatenate str (not "int") to str
您不能连接字符串和整数。这是因为 2 个字符串之间的 +
连接了它们; +
在 2 个整数之间相加。
如果将它们混合使用,则会引发错误。
你可以这样做:
print(f"The name of the plane is {self.ModelName}. It was released by {self.brand}. It has a capacity of {self.capacity}")
这样,您就不必担心变量的数据类型
你可以这样使用 f-strings
print(f"The name of the plane is {self.ModelName}. It was released by {self.brand}.It has a capacity of {self.capacity}")
你的capacity
变量已经归类为int,没有问题。
问题是如果不将 int 转换为 str 就无法打印它。
只需将 intro_plane 函数更改为:
def intro_plane(self):
print(
"The name of the plane is " + self.ModelName +
". It was released by " + self.brand +
". It has a capacity of " + str(self.capacity)
)
你应该很好
为了了解一些背景信息,我试图让自己熟悉对象、类 和 Python 上的属性。
class Plane:
def __init__(self,ModelName,brand,capacity):
self.ModelName = ModelName
self.brand = brand
self.capacity = capacity
def intro_plane(self):
print(
"The name of the plane is " + self.ModelName +
". It was released by " + self.brand +
". It has a capacity of " + self.capacity
)
P1 = Plane("B737", "Boeing", 155)
P1.intro_plane()
我 运行 我在 VsCode 上的代码,这是结果:
TypeError: can only concatenate str (not "int") to str
capacity
是 int
,不是 string
。因此,当您添加到 print
函数时,您需要更改它的类型。
". It has a capacity of " + str(self.capacity)
如错误所述:
TypeError: can only concatenate str (not "int") to str
您不能连接字符串和整数。这是因为 2 个字符串之间的 +
连接了它们; +
在 2 个整数之间相加。
如果将它们混合使用,则会引发错误。
你可以这样做:
print(f"The name of the plane is {self.ModelName}. It was released by {self.brand}. It has a capacity of {self.capacity}")
这样,您就不必担心变量的数据类型
你可以这样使用 f-strings
print(f"The name of the plane is {self.ModelName}. It was released by {self.brand}.It has a capacity of {self.capacity}")
你的capacity
变量已经归类为int,没有问题。
问题是如果不将 int 转换为 str 就无法打印它。
只需将 intro_plane 函数更改为:
def intro_plane(self):
print(
"The name of the plane is " + self.ModelName +
". It was released by " + self.brand +
". It has a capacity of " + str(self.capacity)
)
你应该很好