我有一堂课,有两个功能。我试图将user_input
传递给CreateDirectory.createDir()
,但收到此错误NameError: name 'genDir' is not defined
。如何将user_input
变量传递给CreateDirectory.createDir()
?
我的下面的代码:
class CreateDirectory():
def genDir(name,x=0):
while True:
dir_name = (name + (' ' + str(x) if x is not 0 else '')).strip()
if not os.path.exists(dir_name):
os.mkdir(dir_name)
return dir_name
else:
x = x + 1
def createDir(dir):
genDir(dir)
class PyShell(Cmd):
global default_shell_prompt
default_shell_prompt = ("Shell > ")
prompt = (default_shell_prompt)
def do_exit(self,inp):
PyShellFunc.clearScr()
sys.exit(0)
def do_mkdir(self,inp):
prompt = (default_shell_prompt + "mkdir > ")
running = True
while running:
global user_input
user_input = input(prompt)
if user_input == ("exit"):
running = False
prompt = (default_shell_prompt)
else:
try:
os.mkdir(user_input)
except:
CreateDirectory().createDir()
答案 0 :(得分:1)
您在这里有三个选择: 1)将此函数定义为对象的方法 2)将它们定义为类的方法 3)作为静态方法
1)作为对象的方法
class CreateDirectory():
def genDir(self, name,x=0):
while True:
dir_name = (name + (' ' + str(x) if x is not 0 else '')).strip()
if not os.path.exists(dir_name):
os.mkdir(dir_name)
return dir_name
else:
x = x + 1
def createDir(self, dir):
self.genDir(dir)
2)作为类的方法
class CreateDirectory():
@classmethod
def genDir(cls, name,x=0):
while True:
dir_name = (name + (' ' + str(x) if x is not 0 else '')).strip()
if not os.path.exists(dir_name):
os.mkdir(dir_name)
return dir_name
else:
x = x + 1
@classmethod
def createDir(cls, dir):
cls.genDir(dir)
3)静态方法
class CreateDirectory():
@staticmethod
def genDir(name,x=0):
while True:
dir_name = (name + (' ' + str(x) if x is not 0 else '')).strip()
if not os.path.exists(dir_name):
os.mkdir(dir_name)
return dir_name
else:
x = x + 1
@cstaticmethod
def createDir(dir):
CreateDirectory.genDir(dir)
答案 1 :(得分:1)
我建议将genDir
类设为您的PyShell
类的私有方法,然后将所有这些global
变量替换为实例变量:
class PyShell(Cmd):
def __init__(self, default_shell_prompt = "Shell > "):
self.default_shell_promt = default_shell_prompt
super.__init__() # might not be necessary, not sure what you're doing with Cmd
def exit(self, inp): # Why pass in inp if it's not being used?
PyShellFunc.clearScr() # what is PyShellFunc?
sys.exit(0)
def mkdir(self, inp):
prompt = f"{self.default_shell_prompt}mkdir > "
dir_name = None
while dir_name != "exit":
dir_name = input(prompt)
dir_name = PyShell._get_dir_name()
os.mkdir(user_input)
@staticmethod
def _get_dir_name(name, count = 0):
while True:
dir_name = f"{name} {count if count > 0 else None}"
if not os.path.exists(dir_name):
os.mkdir(dir_name)
return dir_name
else:
return _get_dir_name(name, count + 1)