【问题标题】:calling instances in a class in python在python中调用类中的实例
【发布时间】:2021-07-21 19:21:35
【问题描述】:

我正在参与一个研究项目,试图为我们的一个 AGV:s(自主引导 Viechle)构建一个类。 我不会展示整个班级,但我需要一些指导,以便我可以为我的学生编写易于使用的程序。

所以我的代码看起来像这样(已创建标题):

import requests
import json
import ipaddress
import cmd

MiRTemplate = "http:///api/v2.0.0/"
headers = {}
headers["Content-Type"] = "application/json"
headers["Authorization"] = "Basic

def insertChar(mystring, position, chartoinsert ):
    #check for correct ip input from user
    longi = len(mystring)
    mystring   =  mystring[:position] + chartoinsert + mystring[position:] 
    return mystring 

 class mir(object):
    



    def __init__(self, headers,ip):
        self.headers = headers
        self.ip = ip
        
        print("MiR instance created!")    

    
    def getHw(self):
        host_hw = ip+"/hw/export"
        get_hw = requests.get(host_hw, headers = self.headers)
        print("it worked")
        print(get_hw.headers)
        return   

在我第一次尝试使用我刚刚调用的类时:

mir.getHw()

得到了我要求的打印回复

然后我添加了用户输入,在这种情况下是一个 ip,以便 GET 或 POST 到某个 AGV(我们有 2 个):

#user input
while True:
    try:
        user_ip = input("Enter ip adress of MiR: ")
        ip = ipaddress.ip_address(user_ip)
        print(f'{ip} is correct. Version: IPv{ip.version}')
        #convert back to string and insert into adress line for agv
        ip=str(ip)
        ip=insertChar(MiRTemplate,7,ip) 
        mir = mir(headers,ip)
        mir.getHw
        break
    except ValueError:
        print('ip Adress is invalid')
        continue

这也很有效 现在我的问题是,我尝试添加以下代码:

while True:

    # Create an instance of the MiR class, pass the headers an ip
    
    try:
        
        userinput=input("""Which function do you want to use? \n\n
        1) HardWare Info. \n\n 
 
        type q to quit \n\n
        Please enter the corresponding number and hit enter >>>>> """)
        
        
        if userinput == 1:
            mir = mir(headers,ip)          
            mir.getHw()     
                    
                
        elif userinput== "q":
            break
        
            
    except ValueError:
        print("incorrect input")
        continue

但是在这里我没有从函数中得到打印输出,我该如何解决这个问题? 我还有 8 个函数,比如我想稍后添加的 getHw。

//大卫

【问题讨论】:

    标签: json python-3.x python-requests python-class


    【解决方案1】:

    input 函数在 Python 3 中始终返回 str 对象,因此永远不会产生您所期望的 1 值。您必须尝试将userinput 变量转换为int,或者在这里更简单,只需将其与纯字符串进行比较,如下所示:

    if userinput == '1':
        ...
    

    【讨论】:

    • 非常感谢,我犯了这么愚蠢的错误!
    猜你喜欢
    • 2014-08-06
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 2013-05-31
    • 2010-10-21
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多