python - 如何在python的类中定义全局变量
问题描述
我想在类之外取一个变量,而不是在文件之外。我在课外有一个条件,但我也必须在课堂上使用它。我可以这样做吗?
如果它有效,这是尝试的示例。我想擦除输入部分并使用全局变量。
class ComplexMethods:
ask = input("What type you are writing? (absolute value and phase angle or real and imaginary parts)")
if ask == "real and imaginary parts":
我试过这个但不工作。它给出了未定义的名称“询问”。
class ComplexMethods:
global ask
if ask == "real and imaginary parts":
这是课外。
ask = input("What type you are writing? (absolute value and phase angle or real and imaginary parts)")
if ask == "real and imaginary parts":
firstcomplexreal = float(input("Enter real part of first complex number: "))
firstcompleximaginary = float(input("Enter imaginary part of first complex number: "))
secondcomplexreal = float(input("Enter real part of second complex number: "))
secondcompleximaginary = float(input("Enter imaginary part of second complex number: "))
complexnumbers = ComplexMethods(firstcomplexreal, firstcompleximaginary, secondcomplexreal,
secondcompleximaginary)
解决方案
如果您只想在类之外定义变量,则不需要使用global
关键字,除非您打算修改它。如果您只想读取变量而不修改它,您可以执行类似的操作。
ask = input("What type you are writing? (absolute value and phase angle or real and imaginary parts)")
class ComplexMethods:
if ask == "real and imaginary parts":
pass
if ask == "real and imaginary parts":
firstcomplexreal = float(input("Enter real part of first complex number: "))
firstcompleximaginary = float(input("Enter imaginary part of first complex number: "))
secondcomplexreal = float(input("Enter real part of second complex number: "))
secondcompleximaginary = float(input("Enter imaginary part of second complex number: "))
complexnumbers = ComplexMethods(firstcomplexreal, firstcompleximaginary, secondcomplexreal,
secondcompleximaginary)
推荐阅读
- excel - 如何插入缺少时间的行和单元格
- android - 无法在 NoBar.FullScreen 活动中显示材料警报对话框
- sql - Hive 查询 - 将值除以组中的值的数量
- java - JerseyWebTarget IPv6 支持?
- javascript - 在父级中单击按钮时如何将数据从子级传递给父级
- swift - 如何从另一个孩子 Firebase Swift 中获取孩子
- git - 将 SVN 项目迁移到 Git - 分支和标签完全错误
- python - 缺少 Spyder 依赖项 qtconsole
- php - PHP:恢复转义的Unicode字符
- excel - 在excel中获取VBA代码以查找文件并打开它