簡體   English   中英

如何通過傳遞其名稱來打印現有變量

[英]How to print an existing variable by passing its name

例如:

class abc():
    def __init__(self):
        self.john = 'a'
        self.mike = 'b'

    def d(self, x):
        print(self.x)

m = abc()
# m.d('john')
# m.d(john)

如果我嘗試運行 md('john') 我會得到 'AttributeError: 'abc' object has no attribute 'x'' 如果我嘗試運行 md(john) 我會得到 'NameError: name 'john' is not defined'。 我該如何修改它以使其正常工作?

使用getattr() 它允許您從字符串中獲取屬性。

代碼:

class abc():
    def __init__(self):
        self.john = 'a'
        self.mike = 'b'

    def d(self, x):
        print(getattr(self, x))

m = abc()
m.d('john')

輸出:

a

使用 Python 的getattr()

class abc():
    def __init__(self):
        self.john = 'a'
        self.mike = 'b'

    def d(self, x):
        print(getattr(self, x))

m = abc()
m.d('john')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM