这可能是我的强迫症,但我写了一些代码,我只是想知道是否有一种优雅的方法来更改传递给 python 类中函数的属性?我下面有一些示例代码(我正在尝试更改 on_message 的值):
# my_class is defined in an external library
class my_class:
def __init__(self, stream_url="wss://stream.default:6969/ws", on_message=None):
super().__init__(stream_url, on_message=on_message)
def my_function(self, key: str, **kwargs):
# do stuff to key and kwargs
# my python code
ws_client = my_class(stream_url="wss://stream.actual:6969/ws") # this is at the top of the file where all other declarations are made, as there is no on_message value passed to the class, it's value is None as per __init__ function
def do_stuff_with_message(): # this happens about 3/4 through
# do stuff to with the message
ws_client = my_class(on_message=do_stuff_with_message) # this works but seems clumsy and like a redeclaration. Is there a more pythonic way of doing this?
ws_client.my_function(key="Dante")
如上所述,代码有效,我只是在寻找更简洁的解决方案,甚至可能是 do_stuff_with_message 的前向声明。任何建议,将不胜感激。谢谢。
感谢大家的帮助和评论。我设法用(一种前向声明)“修复”它:
# my_class is defined in an external library
class my_class:
def __init__(self, stream_url="wss://stream.default:6969/ws", on_message=None):
super().__init__(stream_url, on_message=on_message)
def my_function(self, key: str, **kwargs):
# do stuff to key and kwargs
# my python code
def Do_Stuff_With_Message():
do_stuff_with_message()
ws_client = my_class(stream_url="wss://stream.actual:6969/ws", on_message=Do_Stuff_With_Message) # this is at the top of the file where all other declarations are made, as there is no on_message value passed to the class, it's value is None as per __init__ function
def do_stuff_with_message(): # this happens about 3/4 through
# do stuff to with the message
ws_client.my_function(key="Dante")
再次感谢。
首先,看起来您正在用
ws_client
中的类的新实例覆盖 ws_client = my_class(on_message=do_stuff_with_message)
。如果您想添加或更改属性,可以使用 ws_client.on_message = do_stuff_with_message
。
另外,
super().__init__
用于在继承时初始化父类。您不会在这里执行此操作,因此不需要。
class my_class:
def __init__(self, stream_url="wss://stream.default:6969/ws"):
# super().__init__(stream_url, on_message=on_message) does not do anything as my_class is not inheriting from another class
self.stream_url = stream_url
def my_function(self, key: str, **kwargs):
# do stuff to key and kwargs
ws_client = my_class(stream_url="wss://stream.actual:6969/ws")
def do_stuff_with_message():
# do stuff to with the message
ws_client.on_message = do_stuff_with_message # on_message does not need to be declared in __init__.
# In your original code you created a new instance or your class. This code modifies the existing object
ws_client.my_function(key="Dante")