我知道這個標題可能令人困惑(抱歉:我比較新),但這個描述應該清楚。基本上,我已經在一個帶有引數的類中創建了一個函式,如果未指定,我希望該引數默認成為該類的一個實體。
這是我認為可行的:
class Agent:
def __init__(self, value = dict):
self.value = value
def arbitrary(self, other_instance = self.__class__({})):
print(other_instance.value.get('placeholder', 0))
但是,它聲稱 self 沒有定義。從理論上講,我可以簡單地做
def arbitrary(self, other_instance = None):
if other_instance is None:
other_instance = self.__class__({})
print(other_instance.value.get('placeholder', 0))
然而,這很拼湊,所以我想知道在我訴諸類似的東西之前是否有辦法在引數默認值中做到這一點。
uj5u.com熱心網友回復:
對于您的實際問題,可能有更好的解決方案,但由于您沒有分享這些細節,所以很難說到底是什么。
但是,對于您給出的示例,如果other_instance是None,value將是一個空dict的,因此對的呼叫.get()只能 return 0。
所以,這是等價的:
def arbitrary(self, other_instance = None):
if other_instance is None:
print(0)
else:
print(other_instance.value.get('placeholder', 0))
這完全避免了一次性實體的構建。
您的實際用例可能會發生更多事情,但可能還有比即時創建空實體更好的解決方案。如果沒有,那么您擁有的解決方案None就是預期的方法。
(注意:在第一個示例的建構式中設定valuetodict實際上將其設定為type,而不是空實體,這可能是您想要的 - 但是,這樣做會導致關于可變默認值的警告,并且正確的解決方案是在正文中使用None和初始化)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/453148.html
標籤:Python python-3.x 功能 班级 在里面
