无法将 self.instance_variable 作为默认值传递到类方法中

问题描述 投票:0回答:1

我有一个类和方法,我试图将

self.instance_variable
作为默认值传递,但无法传递。让我举例说明:

from openai import OpenAI

class Example_class:
    def __init__(self) -> None:
        self.client = OpenAI(api_key='xyz')
        self.client2 = OpenAI(api_key='abc')
    
    def chat_completion(self, prompt, context, client=self.client, model='gpt-4o'):
        # Process the prompt
        messages = [{"role": "system", "content": context}, {"role": "user", "content": prompt}]
        response = client.chat.completions.create(
            model=model,
            messages=messages,
            temperature=0.35, # this is the degree of randomness of the model's output
        )
        return response.choices[0].message.content
    
    def do_something(self):
        self.chat_completion(prompt="blah blah blah", context="fgasa")

您会看到,尝试将

self.client
传递到
chat_completion
方法时出现错误。我哪里错了?

python class methods instance-variables
1个回答
0
投票

你根本不能这样做。就像其他人一样,将“自我”理解为一个论点(确实如此)。 您无法直接从函数头访问它

执行此操作的一种“正确”方法是将默认值定义为 None 并检查其内容:

Class Example_class:
    def chat_completion(self, prompt, context, client=None, model='gpt-4o'):
        client = client or self.client # this will ensure client is never None.
        # Process the prompt
© www.soinside.com 2019 - 2024. All rights reserved.