如何解决int()函数base 10无效字面量错误?附Python代码场景
The problem here is that your physical() function permanently changes the moons attribute of the Planet instance from an integer to a string (like "1 moon"). When you call collide() afterward, it tries to add 1 to this string, which triggers the ValueError you’re seeing.
The Right Approach: Keep moons as an Integer
Instead of modifying the actual moons attribute type, we should only format it into a descriptive string when we need to display it. This way, the underlying integer value stays intact for methods like collide() that rely on numeric operations.
Modified Code
Here’s the adjusted version of your code with the fix:
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 # This stays an integer throughout 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): # Generate moon description without altering the original attribute if Planet.moons == 1: moon_desc = f"{Planet.moons} moon" else: moon_desc = f"{Planet.moons} moons" return (f"{Planet.name} has a volume of {volume(Planet)} cubic km, a surface area of {surface(Planet)} sq. km, and {moon_desc}") def dynamic(Planet): period = 2 * math.pi * Planet.orbital_radius * math.sqrt(Planet.orbital_radius / mu) return (f"{Planet.name} has a year of approximately {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()) # Now works correctly, returns 2
Key Changes Explained:
- In the
physical()function, we create a temporarymoon_descstring instead of overwritingPlanet.moons. This preserves the integer value ofmoonsfor thecollide()method. - Used f-strings for cleaner, more readable string formatting (this is optional but recommended).
A Fragile Workaround (Not Recommended)
If you absolutely couldn’t avoid modifying the moons attribute to a string, you could extract the integer from the string in the collide() method. But this is brittle—any change to the string format would break the code:
def collide(self): # Extract integer from the string (not ideal) current_moons = int(self.moons.split()[0]) new_moons = current_moons + 1 self.moons = f"{new_moons} moon" if new_moons == 1 else f"{new_moons} moons" return new_moons
Storing raw numeric data in attributes is always the better practice for maintainability.
内容的提问来源于stack exchange,提问作者user12245018

