我将如何解决这个以 10 为底的错误的 int() 无效文字?

How would I work around this invalid literal for int() with base 10 error?

import math

# The standard gravitational parameter for the sun
mu = 1.327 * math.pow(10, 20)

class Planet:
  def __init__(self, name, radius, moons, orbital_radius):
    self.name = name
    self.radius = radius
    self.moons = moons
    self.orbital_radius = orbital_radius

  def collide(self):
    self.moons = self.moons + 1
    return self.moons


def volume(Planet):
  v = (4 / 3) * math.pi * math.pow(Planet.radius, 3)
  return str(v)

def surface(Planet):
  area = 4 * math.pi * math.pow(Planet.radius, 2)
  return str(area)  

def physical(Planet):
  if Planet.moons == 1:
    Planet.moons = str(Planet.moons) + " moon"
  else:
    Planet.moons = str(Planet.moons) + " moons"
  return (Planet.name + " has a volume of " + volume(Planet) + " cubic km, a surface area of " + surface(Planet) + " sq. km, and " + Planet.moons)

def dynamic(Planet):
  period = 2 * math.pi * Planet.orbital_radius * math.sqrt(Planet.orbital_radius / mu)
  return (Planet.name + " has a year of approximately " + str(period // (60 * 60 * 24)) + " days")

Earth = Planet('Earth', 6371, 1, 1.496 * math.pow(10, 11))
Jupiter = Planet('Jupiter', 69911, 79, 7.786 * math.pow(10, 11))

print(physical(Earth))
print(physical(Jupiter))
print(dynamic(Earth))
print(dynamic(Jupiter))

print(Earth.collide())

我知道 self.moons 由于物理功能而变成了一个字符串,但我将如何再次变成一个整数。这似乎是不可能的,因为整数和字符串被存储为它的值,这就是为什么我在尝试 print(Earth.collide())

时收到错误消息 ValueError: invalid literal for int() with base 10: '1 moon'

只需将字符串划分为 space 并取第一部分:

int(self.moon.partition(" ")[0])

您也可以使用 str.split(),但对于 'only need to split once' 情况,分区会快一点。

更好的 方法是不将 .moons 属性设置为字符串。保持它是一个整数,不需要替换它只是为了用信息格式化一个漂亮的字符串:

def physical(Planet):
    if Planet.moons == 1:
        moons = str(Planet.moons) + " moon"
    else:
        moons = str(Planet.moons) + " moons"
    return (Planet.name + " has a volume of " + volume(Planet) + " cubic km, a surface area of " + surface(Planet) + " sq. km, and " + moons)

你可能想看看 formatted string literals or the format string syntax:

def physical(Planet):
    moons = f"{Planet.moons} moon"
    if Planet.moons != 1:
        moons += 's'
    return (
        f"{Planet.name} has a volume of {volume(Planet)} cubic km, a surface "
        f"area of {surface(Planet)} sq. km, and {moons}"
    )

无论哪种方式,通过使用局部变量 moons 来包含格式化的 卫星数量 值,您不会更改 Planet.moons 值,因此不必担心如何返回到它再次成为整数。

我建议在 def physical(Planet) 中坚持使用 local/private 变量,因为它不会在其他任何地方使用,只是值的格式。

def physical(Planet):
  if Planet.moons == 1:
    _planet_moons = str(Planet.moons) + " moon"
  else:
    _planet_moons = str(Planet.moons) + " moons"
  return (Planet.name + " has a volume of " + volume(Planet) + " cubic km, a surface area of " + surface(Planet) + " sq. km, and " + _planet_moons)

这会阻止您来回转换价值。