【问题标题】:Trying to call a function from a function in a class尝试从类中的函数调用函数
【发布时间】:2019-03-14 01:36:21
【问题描述】:

我不断收到以下错误

g:\python_test>py3 lib\libtest.py p = g:\python_test\SqlLogon.txt 回溯(最近一次通话最后): 文件“lib\libtest.py”,第 43 行,在

i.printit('c:\mylog.log')

文件“lib\libtest.py”,第 32 行,在 printit 中

s = wos()

NameError: name 'wos' 未定义

如果我删除对 os 的调用并让 s = 'WINDOWS' 一切正常。 为什么我不能调用该函数?以下是给出问题的代码!

import sys
import platform

import os

import subprocess
class utl:

    def __init__(self,path):
        self.path = path
        print ('p = ' + self.path)

    def usr(self):

        lc = open(self.path,'r')

        up = lc.readlines()
        u = up[0]
        u = u.strip('\n')
        p = up[1]
        p = p.strip('\n')

        return u,p

    def wos(self):
        p = platform.system()        
        print ('type = ' + str(type(p)))

        return p.upper()

    def printit(self,filetoprt):
        s = wos()   # undefined wos
        #s = "WINDOWS"
        print ('os1 = ' + s  + ' ' + filetoprt)
        if s == ('WINDOWS'):
            os.startfile(filetoprt,'print')

#x = LogonSql.usr('g:\python_test\lib\jcd.txt')
i= utl('g:\python_test\SqlLogon.txt')

p = i.usr()
#t = i.wos()
i.printit('c:\mylog.log')

【问题讨论】:

标签: python


【解决方案1】:

wos 是你的班级成员,你应该用

self.wos()

【讨论】:

  • 感谢工作!我只是想学习 Python,想知道是否有人对如何最好地处理 Python 中的缩进有一些提示。使用 uedit32???
  • uedit32 已经过时了,尝试一些现代化的代码编辑器,比如 sublime、atom、MS code 等。
【解决方案2】:

wos() 是绑定到utl 类实例的方法,因此您需要这样引用它们。

s = wos() 替换为s = self.wos()。否则,您的代码会尝试访问您尚未定义的全局范围(类外部)上的函数 wos()

【讨论】:

    猜你喜欢
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多