[英]Python: Calling a class based on variable's value
Essentially what I want this code to do, is replace (systemType).clear()
with either unix.clear
or windows.clear
. 从本质上讲,我想要此代码执行的操作是用
unix.clear
或windows.clear
替换(systemType).clear()
。 Is this even possible? 这有可能吗?
if(platform.system()=="Windows"):
systemType="windows"
else:
systemType="unix"
class unix:
def clear():
os.system('clear')
class windows:
def clear():
os.system('cls')
print("Detecing systemType")
time.sleep(1)
(systemType).clear()
The error is AttributeError: 'str' object has no attribute 'clear'
错误是
AttributeError: 'str' object has no attribute 'clear'
If you move the assignment of systemType
to after the class definitions, you can assign it the classes themselves rather than their names: 如果将
systemType
的分配systemType
类定义之后,则可以为其分配类本身而不是其名称:
class unix:
def clear():
os.system('clear')
class windows:
def clear():
os.system('cls')
if platform.system()=="Windows":
systemType = windows
else:
systemType = unix
print("Detecing systemType")
time.sleep(1)
systemType.clear()
import os
if os.name == "nt":
os.system("cls") #windows
else:
os.system("clear") #unix
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.