即使它是python3函数也没有定义 [英] python3 function not defined even though it is

查看:160
本文介绍了即使它是python3函数也没有定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试调用changeProfile函数时,即使明确定义了错误,我仍会收到错误getAuthCode未定义。为什么我一直得到这个错误?我究竟做错了什么?它曾经从我所记得的东西开始工作,但现在突然间它没有。任何帮助将不胜感激:)

pre $ import os,re,json,socket,random,select,threading,time,sys
从urllib.request中导入urllib.request作为urlreq
import quote,unquote
import urllib.parse $ b $ class miscellanous:
Main class。
def __init __():
初始化做些什么。
pass
def getAuthCode(u,p):
获取认证
尝试:
data = urllib.request.urlopen('http://chatango.com/login',urllib.parse.urlencode({'user_id' :','password':p,'storecookie':'on','checkerrors':'yes'})。encode())。headers
除了Exception:e:print(Error:Auth request: ():
如果x.lower()=='set-cookie':
returned = re.compile(r)%s%e)
在data.items auth\.chatango\.com?=?([^;] *),re.IGNORECASE).search(y)
如果返回:
ret = returned.group(1)
如果ret ==:增加ValueError(错误:无法获得认证:用户名/密码错误)
返回ret

$ b $ def createAccount(u,p):
用指定的用户名和密码创建一个帐户。
try:
resp = urllib.request.urlopen(http://chatango.com/signupdir,urllib.parse.urlencode({email:accmaker+ str(random.randrange(1,1000000000000))+@ hotmail.com,login:u,password:p,password_confirm:p,storecookie:on,checkerrors:yes})。encode())
fu = str(resp.read())
resp.close()
如果在fu中显示屏幕名称:r =错误:无法创建用户:已存在。
else:r =用户已创建,如果不起作用,请尝试其他用户名。
返回r
除外:return错误:无效或缺少参数。
def createGroup(u,p,g,d =Description。,m =所有者消息):
使用用户名,密码,组名,描述和
尝试:
g = g.replace(, - )
resp = urllib.request.urlopen(http://chatango.com/ creategrouplogin,urllib.parse.urlencode({User-Agent:Mozilla / 5.0,uns:0,p:p,lo:u,d:d,u :g,n:m})。encode())
fu = str(resp.read())
resp.close()
如果groupexists r =错误:无法创建组:已存在。
else:r =该群组已创建,如果无效,请尝试另一个群组名称。单击< a href ='http://%s.chatango.com/'target ='_ blank' > [[here]]< a>去新组。
返回r
除外:return错误:无效或缺少参数。
def changeProfile(u,p,m =Default,e =accmaker+ str(random.randrange(1,1000000000000))+@ hotmail.com,l =Norway,g = M,a =18):
试试:
resp = urlreq.urlopen('http://'+.lower()+'。chatango.com/updateprofile?& d&安培; PIC&安培; S ='+ getAuthCode(U,p),urllib.parse.urlencode({ show_friends: 检查, DIR: 检查, checkerrors: 是, UNS: 1,line:m,email:e,location:l,gender:g,age:a})。encode())
return成功。
除了Exception:e
返回%s%e
def checkOnlineStatus(u):
检查预定义的用户名是在线还是离线。如果在urlreq.urlopen(http://+ u.lower()+.chatango.com).read()。decode():return'< b>< b> ;字体颜色= #00FF00 >在线< /字体>< / b个
,否则:返回< b取代;<字体颜色= '#FF0000' >离线< /字体>< ; / b>中
resp.close()
def checkUserGender(u):
获取预定义用户名的性别。
resp = urlreq.urlopen(http: ().http://st.chatango.com/profileimg/%s/%s/%s/mod1.xml%(u.lower()[0],u.lower()[1],u.lower()))
try:ru = re.compile(r's>(。*?)< / s>',re.IGNORECASE).search(resp.read()。decode())。group 1)
除外:ru =?
ret = unquote(ru)
resp.close()
if ret ==M:r =Male
elif ret ==F:r = 女
elif ret ==?:r =未指定
返回r
def changeBackGround(u,p,x,透明度=无):

color = quote(x.split()[0])
try:image = x.split()[ 1]
除外:image = None
如果color和len(color)== 1:
color = color * 6
如果color和len(color)== 3:
color + = color
elif color and len(color)!= 6:
返回False
if transparent!= None and abs(transparency)> 1:
透明度= abs(透明度)/ 100
data = urllib.request.urlopen(http://fp.chatango.com/profileimg/%s/%s/%s/msgbg.xml%(u [ 0],u [1],u.lower()))。read()。decode()
data = dict([x.replace(''','').split( ('(\ w + =。*?)',data)[1:]])
data [p] = p
data [ lo] = u
如果color:data [bgc] = color
if transparent!= None:data [bgalp] = abs(透明度)* 100
如果图像!= None:data [useimg] = 1 if bool(image)else 0
data12 = urllib.parse.urlencode(data)
data13 = data12.encode()
der = urllib.request.urlopen(http://chatango.com/updatemsgbg,data13).read()
def checkIfGroupExists(g):
检查预定义组是否存在。
i = urlreq.urlopen('http://'+g+'.chatango.com').read().decode()
if'< table id =group_table'in i :return True#这个聊天确实存在!
else:return False#这个聊天不存在。
i.close()


解决方案

您显示的所有函数都是杂项 class,所以要访问它们,你需要在类名前加前缀。要引用 getAuthCode 函数,您可以使用 miscellaneous.getAuthCode



但是,看起来你不应该真的在这里上课。您绝不会创建杂项的实例,也不会将这些函数设置为作为方法运行。所以,可能正确的答案是摆脱文件顶部的 class miscellaneous:声明,然后是一个级别的所有函数的unindent。



(请注意,在Python 2中,如果您保留该类,则会遇到其他问题:未绑定的方法需要将其第一个参数作为其类(或子类)的实例。在那种情况下,你需要在任何根本不希望获得实例的函数上使用 staticmethod 装饰器。)


when I try to call the changeProfile function, I keep getting the error "getAuthCode is not defined" even though it is clearly defined. Why do I keep getting this error? What am I doing wrong? It used to work from what I remember, but now all of a sudden it doesn't. Any help would be appreciated :)

import os,re,json,socket,random,select,threading,time,sys
import urllib.request as urlreq
from urllib.request import quote,unquote
import urllib.parse
class miscellanous:
    """Main class."""
    def __init__():
        """What to do on initalizing."""
        pass
    def getAuthCode(u, p):
        """Get authentification code from username and password specified."""
        try:
            data=urllib.request.urlopen('http://chatango.com/login',urllib.parse.urlencode({'user_id': u, 'password': p, 'storecookie': 'on', 'checkerrors': 'yes'}).encode()).headers
        except Exception as e: print("Error: Auth request: %s" % e)
        for x, y in data.items():
            if x.lower() == 'set-cookie':
                returned = re.compile(r"auth\.chatango\.com ?= ?([^;]*)", re.IGNORECASE).search(y)
                if returned:
                    ret = returned.group(1)
                    if ret == "": raise ValueError("Error: Unable to get auth: Error in username/password.")
                    return ret


    def createAccount(u, p):
        """Create an account with the username and password specified."""
        try:
            resp=urllib.request.urlopen("http://chatango.com/signupdir", urllib.parse.urlencode({"email": "accmaker"+str(random.randrange(1,1000000000000))+"@hotmail.com", "login": u, "password": p, "password_confirm": p, "storecookie": "on", "checkerrors": "yes"}).encode())
            fu=str(resp.read())
            resp.close()
            if "screen name has been" in fu: r = "Error: User could not be created: Already exists."
            else: r = "The user was created. If it didn't work, try another username."
            return r
        except: return "Error: Invalid or missing arguments."
    def createGroup(u, p, g, d="Description.", m="Owner message."):
        """Creates a group with the username, password, group name, description and owner message specified."""
        try:
            g=g.replace(" ","-")
            resp=urllib.request.urlopen("http://chatango.com/creategrouplogin",urllib.parse.urlencode({"User-Agent": "Mozilla/5.0", "uns": "0", "p": p, "lo": u, "d": d, "u": g, "n": m}).encode())
            fu=str(resp.read())
            resp.close()
            if "groupexists" in fu: r = "Error: Group could not be created: Already exists."
            else: r = "The group was created. If it didn't work, try another group name. Click <a href='http://%s.chatango.com/' target='_blank'>[[here]]<a> to get to the new group."
            return r
        except: return "Error: Invalid or missing arguments."
    def changeProfile(u, p, m="Default", e="accmaker"+str(random.randrange(1,1000000000000))+"@hotmail.com", l="Norway", g="M", a="18"):
        try:
            resp = urlreq.urlopen('http://'+u.lower()+'.chatango.com/updateprofile?&d&pic&s='+getAuthCode(u, p), urllib.parse.urlencode({"show_friends": "checked", "dir": "checked", "checkerrors": "yes", "uns": "1", "line": m, "email": e, "location": l, "gender": g, "age": a}).encode())
            return "The profile change was successful."
        except Exception as e:
            return "%s" % e
    def checkOnlineStatus(u):
        """Check if the predefined username is online or offline."""
        if "Chat with" in urlreq.urlopen("http://"+u.lower()+".chatango.com").read().decode(): return '<b><font color="#00ff00">Online</font></b>'
        else: return "<b><font color='#ff0000'>Offline</font></b>"
        resp.close()
    def checkUserGender(u):
        """Get the gender for the predefined username."""
        resp=urlreq.urlopen("http://st.chatango.com/profileimg/%s/%s/%s/mod1.xml" % (u.lower()[0], u.lower()[1], u.lower()))
        try: ru=re.compile(r'<s>(.*?)</s>', re.IGNORECASE).search(resp.read().decode()).group(1)
        except: ru="?"
        ret=unquote(ru)
        resp.close()
        if ret=="M": r="Male"
        elif ret=="F": r="Female"
        elif ret=="?": r="Not specified"        
        return r
    def changeBackGround(u, p, x, transparency=None):
        """Update the user's bg using the predefined username, password and bg color."""
        color=quote(x.split()[0])
        try: image=x.split()[1]
        except: image=None
        if color and len(color)==1:
            color=color*6
        if color and len(color)==3:
            color+=color
        elif color and len(color)!=6:
            return False
        if transparency!=None and abs(transparency)>1:
            transparency = abs(transparency) / 100
        data=urllib.request.urlopen("http://fp.chatango.com/profileimg/%s/%s/%s/msgbg.xml" % (u[0], u[1], u.lower())).read().decode()
        data=dict([x.replace('"', '').split("=") for x in re.findall('(\w+=".*?")', data)[1:]])
        data["p"]=p
        data["lo"]=u
        if color: data["bgc"] = color
        if transparency!=None: data["bgalp"]=abs(transparency) * 100
        if image!=None: data["useimg"]=1 if bool(image) else 0
        data12=urllib.parse.urlencode(data)
        data13=data12.encode()
        der=urllib.request.urlopen("http://chatango.com/updatemsgbg", data13).read()
    def checkIfGroupExists(g):
        """Check if the predefined group exists."""
        i = urlreq.urlopen('http://'+g+'.chatango.com').read().decode()
        if '<table id="group_table"' in i: return True#"This chat does exist!"
        else: return False#"This chat doesn't exist."
        i.close()

解决方案

All of the functions you've shown are part of the miscellaneous class, so to access them, you need to prefix them with the class name. To refer to the getAuthCode function, you'd use miscellaneous.getAuthCode.

But, it doesn't seem like you should really be using a class here. You never create instances of miscellaneous, nor are the functions set up to be run as methods. So, probably the right answer is to get rid of the class miscellaneous: declaration at the top of the file, and then to unindent all the functions one level.

(Note, in Python 2 you'd have an additional issue if you kept the class: Unbound methods required that their first argument be an instance of their class (or a subclass). In that situation, you'd need to use the staticmethod decorator on any functions that did not expect to get an instance at all.)

这篇关于即使它是python3函数也没有定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆