![](/img/trans.png)
[英]How to change the value of a module variable from within an object of another module?
[英]How to change class object parameters from another module (python)
所以我四處搜尋,找不到答案。 我正在尋找從模塊中主文件中創建的對象更改參數的方法。 例如,我在這里用一個簡單的代碼來測試它:
-這是我的主文件,我從中創建對象並定義一些屬性
import class_test_2
class dog():
name=''
spots=0
def add_spots(self):
self.spots+=1
def main():
fido=dog()
fido.name='Fido'
print('Fido\'s spots: ',fido.spots)
fido.add_spots()
print('Fido\'s spots: ',fido.spots)
class_test_2.class_test()
print('Fido\'s spots: ',fido.spots)
if __name__=='__main__':
main()
-這是一個模塊,我想從中使用函數來更改主文件中的屬性
from class_test_1 import dog
def class_test():
fido.add_spots()
-所以我的問題是我該怎么辦/為什么上面這段代碼不起作用? 單獨運行main函數會顯示fido的斑點每次打印都增加1。 但是,運行調用模塊的代碼會產生NameError,因此即使我設法導入了該類,我的模塊也無法識別該類的存在。 在此先感謝您的幫助。
您的變量“ fido”僅在“ main”函數中定義。 您必須為“ class_test”函數提供變量。
例如:
class_test_2.class_test(fido)
然后,您的class_test
函數將獲取一個參數。 您可以自由選擇名稱。 我在示例中使用the_dog
:
def class_test(the_dog):
the_dog.add_spots()
在這種情況下, the_dog
與fido
指向同一個dog
類實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.