簡體   English   中英

如何使用變量調用 function?

[英]How do i use a variable to call a function?

我用函數和屬性編寫了一個 class。 我想在不輸入我想要的確切名稱的情況下制作 class 的 object。 非工作示例:

# define the class
class Member:
    def __init__(self):
        self.member_money = 0
        self.member_last_cooldown = 0
    def work(self):
            print("you worked")
            self.member_money += 10
#example #1 make a object with the text that the user submitted with input()
variable1 = input("desired name of object")
variable1 = Member()
# it doesnt work as intended, it just makes an object called variable1, instead of the
# calling it the value of variable1

# example #2 call a function of an object with a variable
member1 = Member()
variable2 = input("desired name of function")
member1.variable2()
# if i would type in work, i want it to print "you worked" as seen in the work function of the class that member1 belongs to
# but instead, it takes variable2 literally, as a string and it raises this: AttributeError: 'Member' object has no attribute 'variable2'```

關於您的第一個示例,如果您希望能夠使用用戶提交的文本訪問任意對象,您可以嘗試使用字典數據結構。

我還將擴展您的Member class 以添加first_name屬性以進行說明。

class Member:
    def __init__(self, first_name):
        self.first_name = first_name
        ...
objects = {}

variable = input("first name of member")
objects[variable] = Member(variable)

variable = input("first name of another member")
objects[variable] = Member(variable)

假設用戶沒有在兩個輸入中輸入完全相同的字符串,您的字典現在將包含兩個項目,其中鍵是用戶提交的文本,值是使用first_name屬性創建的 object 作為相同的用戶輸入。

然后,您可以按以下方式訪問代碼中的對象:

variable = input("first name of member to add money to")
objects[variable].member_money += 25

暫無
暫無

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

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