如何在PyCharm中运行Python脚本并进入Python Shell执行交互命令?
How to Run Your Point Class in PyCharm and Test in Python Shell
Got it, let's walk through exactly how to do this step by step, including a heads-up about a common issue you'll hit with the addition part:
Step 1: Save Your Code in PyCharm
- First, create a new Python file in your PyCharm project (right-click your project → New → Python File) — name it something like
point_class.py. - Paste your code into this file:
class Point: def __init__(self, x = 0, y = 0): self.x = x self.y = y # Define __str__() method in our class can control how it gets printed. def __str__(self): return "({0},{1})".format(self.x, self.y)
Step 2: Launch Python Shell with Your Class Loaded
You have two easy ways to do this in PyCharm:
Option 1: Use PyCharm's Built-in Python Console
- At the bottom of your PyCharm window, click the Python Console tab (if you don't see it, go to View → Tool Windows → Python Console).
- The console will load your project's Python interpreter. To import your
Pointclass, run this command:
(Make sure the filename matches what you saved earlier — if you named itfrom point_class import Pointpoint.py, usefrom point import Point)
Option 2: Run the File in Interactive Mode via Terminal
- Open PyCharm's Terminal tab (bottom of the window, next to Python Console).
- Navigate to the folder where you saved your
point_class.pyfile (if you're not already there, usecd path/to/your/file). - Run this command to launch an interactive Python shell with your class pre-loaded:
python -i point_class.py
Step 3: Execute Your Commands in the Shell
Once your shell is ready and the Point class is available, run these commands one by one:
>>> p1 = Point(2,3) >>> p2 = Point(-1,2) >>> p1 + p2
Important Note: You'll Hit an Error Here!
Your current code defines __str__ but doesn't implement the __add__ method — Python doesn't know how to add two Point objects by default. To fix this, add this method to your Point class:
def __add__(self, other): # Add the x and y coordinates separately return Point(self.x + other.x, self.y + other.y)
Now when you run p1 + p2, it'll return a new Point object with coordinates (1,5), and since you have __str__ defined, printing it will show (1,5).
内容的提问来源于stack exchange,提问作者PhyAH
相关产品推荐
相关产品推荐

