[英]Is there a way to access an attribute outside a class?
我想訪問 class 之外的屬性,但即使在谷歌搜索之后,我也沒有看到針對這個特定問題的任何類似解決方案。
class test():
def __init__(self) -> None:
pass
def testpy(self):
self.x = 'Hello world'
value = test().testpy.x
print(value)
>> AttributeError: 'function' object has no attribute 'x'
我認為您對屬性是什么感到困惑。
在您的代碼中X
是成員 function testpy
中的局部變量。 X
僅存在於 function 中,並在 function 退出時被刪除。
如果你想要一個成員,寫self.x = 'Hello world'
。 這將創建並存儲一個名為 x 的數據成員。 此外,當您編寫test().testpy().x
時,您正在調用成員 function testpy()
然后嘗試在返回結果上調用.x
,這顯然會中斷。
在您的代碼中, x
是 function 內的局部變量,而不是 class 屬性。 您可以返回該變量:
class test():
def __init__(self) -> None:
pass
def testpy(self):
x = 'Hello world'
return x
value = test().testpy()
print(value)
請再從 go 到 python class 教程。 testpy
是 class Test
的 function ,它在上面的代碼中返回 None 。 x
是 class Test
的屬性,而不是 function 'testpy'
class Test():
def __init__(self):
pass
def testpy(self):
self.x = 'Hello world'
t = Test()
t.testpy()
value = t.x
print(value)
我認為您混淆了本地 scope、class 屬性和全局 scope。
您可以通過以下三種方式之一實現您的結果:
return
關鍵字返回本地值global
鍵世界創建一個全局范圍的變量。 強烈不推薦class test:
def __init__(self) -> None:
self.x = "Hello world"
pass
def testpy(self):
self.x = "Hello world"
x = "Hello world"
global Y
Y = "Hello world - global"
return x
object = test()
value_via_objects_attribute = object.x
value_via_objects_method = object.testpy()
value_via_global = Y
print(value_via_objects_attribute)
print(value_via_objects_method)
print(value_via_global)
我認為您將 testpy() function 與您的構造函數 - init方法混淆了。 在 python 中,您可以通過調用 class 來初始化一個新的 object,就好像它是一個 ZC1C425268E68385D1AB5074C1 一樣,它是一個 ZC1C425268E68385D1AB5074C1"。 當您調用此 function 時,將調用init方法,並返回一個新的 object(自身)。 因此,要在 self 上聲明一個屬性,在init function(您的構造函數)中,您只需編寫“self.x = “Hello World”。
您的問題的完整解決方案如下。
class test():
def __init__(self):
self.x = 'Hello World'
value = test()
print(value.x)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.