AttributeError:“函数”对象在尝试从函数访问变量时没有属性错误

2024-09-28 03:13:16 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我已经在推特机器人上工作了一段时间,只是为了好玩,但我一直被这个问题困扰着。有时有效,有时无效。代码如下:

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'

Tags: textnameinapiidreaddeftweets
2条回答

teste是一个函数而不是类。如果希望在teste上具有属性,请将其设置为如下类:

class teste:
    def __init__():
        tweets = api.home_timeline(2, read_id(FILE_NAME), tweet_mode = 'extended')
        # ...

可以这样称呼:

teste_instance = teste()

通过引用self.x访问teste内部的teste_instance.x

当垃圾收集器执行函数后删除teste.x时,您可以使用全局变量或在函数外部传递创建的变量,从函数返回其值以供进一步传输和使用

例如:

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)


另外,由于缺少所需的库,我没有测试代码的功能,但是除了可能出现的简单错误外,您将获得所需的结果

相关问题 更多 >

    热门问题