Python类找不到属性 [英] Python class can't find attribute
问题描述
基本上,我想运行connect函数,但是我一直收到CMD错误消息类StraussBot没有属性" connectSock",但显然可以看到.我尝试在此处进行搜索,但找不到该问题的任何解决方案.因此,如果您能帮助我找到为什么找不到"connectSock"功能的原因,将不胜感激.
Basically, I want to run the connect function but I keep getting the CMD error message 'class StraussBot has no attribute 'connectSock' but I can obviously see it does. I've tried searching on here and I can't find any resolutions to this issue. SO it will be greatly appreciated if you could help me find why this isn't finding the 'connectSock' function.
代码:
import socket
from config import HOST, PORT, CHANNEL
# User Info
USER = "straussbot" # The bots username
PASS = "oauth:sj175lp884ji5c9las089sm9vvaklf" # The auth code
class StraussBot:
def __init__(self):
self.Ssock = socket.socket()
def connectSock(self):
self.Ssock.connect((HOST, PORT))
self.Ssock.send(str("Pass " + PASS + "\r\n").encode('UTF-8'))
self.Ssock.send(str("NICK " + USER + "\r\n").encode('UTF-8'))
self.Ssock.send(str("JOIN " + CHANNEL + "\r\n").encode('UTF-8'))
if __name__ == "__main__":
print "Starting the bot..."
while True:
straussbot = StraussBot
try:
straussbot.connectSock()
except Exception as e:
print e
推荐答案
您对这里的错误感到困惑.您会为 self.Ssock
获得 AttributeError
,因为您没有实例.
You are getting confused by the error here. You get an AttributeError
for self.Ssock
because you do not have an instance.
您仅在此处创建了对该类的引用:
You only created a reference to the class here:
straussbot = StraussBot
您需要调用该类以产生一个实例:
You need to call the class to produce an instance:
straussbot = StraussBot()
您还在混合制表符和空格:
You are also mixing tabs and spaces:
请注意,第5到9行的缩进方式中有行,而其余的行中有点吗?这些是制表符,Python将其视为 8个空格.因此,您的 connectSock
方法在 __ init __
的 inside 中缩进,而不被视为 StrausBot
上的方法.
Note how lines 5 through 9 have lines in the indentation, but the rest have dots? Those are tabs, and Python sees those as 8 spaces. So your connectSock
method is indented inside of __init__
and not seen as a method on StrausBot
.
您必须坚持使用制表符或正义空格.Python的样式指南强烈建议您仅使用空格.
You'll have to stick to either just tabs or just spaces. Python's styleguide strongly recommends you use spaces only.
这篇关于Python类找不到属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!