如何将方法的返回值传递给另一个方法 Python

How to pass a returned value from method to another one Python

我有两个方法。第一个是从抖音URL中提取用户名,第二个是判断抖音直播当前是直播还是结束。 例如,第一种方法将 URL 作为 '*https://www.tiktok.com/@farahmodel/live*'。它将 return farahmodel 作为用户名。

我想将 return 值传递给第二种方法。有什么想法吗?

使用以下代码:

from TikTokLive import TikTokLiveClient
from TikTokLive.types.events import *
import sys


class TikTok:
    """
    This class is to determine whether a TikTok live video is (live now) or (ended) one.
    """

    @staticmethod
    def url_analysis(url):
        """
        This method will extract the username from the source URL.
        """
        username = ''
        if '/live' in url:
            for part in url.split('/'):
                if '@' in part:
                    username = part
        username = username.replace('@', '')
        return username

    @staticmethod
    def is_live(username):
        """
        This method will check the live room ID if it is valid or not.
        Example of a valid room ID '7099710600141474562'.
        Many events can be used, for example: counting views, comments, likes, etc.
        """
        client: TikTokLiveClient = TikTokLiveClient(unique_id=username)

        @client.on("connect")
        async def on_connect(_: ConnectEvent):
            if client.room_id != 0:
                print('LIVE is running now.')
                sys.exit()

        if __name__ == '__main__':
            try:
                client.run()
                client.stop()
            except Exception as error:
                print(f'Cannot connect due to {type(error).__name__} or Live is ended by the host.')


# Pass the URL.
TikTok.url_analysis(url='https://www.tiktok.com/@farahmodel/live')
TikTok.is_live(username='')  # I want to pass the returned 'username' of url_analysis method.

将 return 值分配给局部变量(例如 username),然后将其作为参数传递给 is_live() 方法调用:

username = TikTok.url_analysis(url='https://www.tiktok.com/@farahmodel/live')
TikTok.is_live(username=username)

看来您正在学习编码基础知识,我建议您查看 lessons/tutorials 关于分配变量和调用 functions/methods。