[英]How to access class method and class variable from a class to another class's instance method in Python?
[英]How to Change a Class Instance's Method in Python?
我想創建一個python庫,這個庫的部分功能涉及創建一個帶有一些用戶定義變量的類實例。 如何讓用戶在所述實例的方法中為類實例編寫自己的條件? 例如,假設我有以下類的實例:
class Test:
def __init__(self, some_value):
self.some_value = some_value
def func(self):
pass
instance = Test(4)
如何讓用戶更改instance.func()
的功能(如何讓用戶訪問對象的變量?
您可以將用戶函數的引用傳遞給init例如:
class Test:
def __init__(self, user_function):
self._function = user_function
def func(self):
return self._function()
def ufunc_1():
return 'Hello world!'
def ufunc_2():
return 'Goodbye cruel world'
t_1 = Test(ufunc_1)
t_2 = Test(ufunc_2)
print(t_1.func())
print(t_2.func())
這樣,對用戶函數的引用存儲在實例變量中。
輸出:
Hello world!
Goodbye cruel world
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.