如何解决AttributeError: 'function' 对象在尝试从函数访问变量时没有属性错误
如果现在已经在 Twitter 机器人上工作了一段时间,只是为了好玩,但我一直被这个单一的问题所困扰。有时它有效,有时它不起作用。代码如下:
def teste():
tweets = api.home_timeline(2,read_id(FILE_NAME),tweet_mode = 'extended')
print('Setup is ok!')
for tweet in reversed(tweets):
if 'carente' in tweet.full_text.lower():
print(str(tweet.id) + ' - ' + tweet.full_text)
api.retweet(tweet.id)
store_the_id(FILE_NAME,tweet.id)
teste.x = 1
elif 'carente' not in tweet.full_text.lower():
teste.x = 0
else:
print('Error no sistema alguem me desconfiguro')
def tweet_timer():
if time.gmtime().tm_min == '10':
api.update_status(f'Farid esteve carente {y} vezes')
else:
return
while True:
teste()
with open('number.txt','r') as f:
read = f.readline
z = int(read())
y = z + teste.x
print(y)
with open('number.txt','w') as f:
write = f.write(str(y))
write
tweet_timer()
time.sleep(40)
我正在尝试从函数中访问 teste.x 变量,但是当我在 y = z + teste.x 处这样做时,它给出了以下错误:
Traceback (most recent call last):
File "c:\Users\fredg\Desktop\Programação\Python\Twitter Bot\Website\Word.py",line 69,in <module>
y = z + teste.x
AttributeError: 'function' object has no attribute 'x'
解决方法
垃圾收集器执行函数后删除teste.x,可以使用全局变量或将created传递给函数外,从函数返回其值以供进一步调用使用。
示例:
def teste(x: int) -> int:
tweets = api.home_timeline(2,read_id(FILE_NAME),tweet_mode="extended")
print("Setup is ok!")
for tweet in reversed(tweets):
if "carente" in tweet.full_text.lower():
print(str(tweet.id) + " - " + tweet.full_text)
api.retweet(tweet.id)
store_the_id(FILE_NAME,tweet.id)
x = 1
elif "carente" not in tweet.full_text.lower():
x = 0
else:
print("Error no sistema alguem me desconfiguro")
return x
def tweet_timer():
if time.gmtime().tm_min == "10":
api.update_status(f"Farid esteve carente {y} vezes")
else:
return
x = 0
while True:
x = teste()
with open("number.txt","r") as f:
read = f.readline
z = int(read())
y = z + x
print(y)
with open("number.txt","w") as f:
write = f.write(str(y))
write
tweet_timer()
time.sleep(40)
附言由于缺少所需的库,我没有测试代码的功能,但是除了简单可能的错误,你会得到你需要的结果
,teste
是一个函数不是一个类。如果您想在 teste
上拥有属性,请将其设为这样的类:
class teste:
def __init__():
tweets = api.home_timeline(2,tweet_mode = 'extended')
# ...
这样称呼它:
teste_instance = teste()
通过引用 teste_instance.x
访问 teste
内的 self.x
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。