我如何通过输入访问类

时间:2015-10-27 22:35:37

标签: python class

我把一个小的测试代码放在一起,只是为了演示我在尝试输入带输入的类时遇到的错误。没有什么比得到特定错误更好或更好。

代码:

class people(object):
    def deposit():
        print("depositing")
    def withdraw():
        print("withdrawing")
John = people()
selection = input("Type John: ")
selection.deposit

错误:

[evaluate classes.py]
Type John: John
Traceback (most recent call last):
  File "c:\Users\Peter\Desktop\Desktop 2\Python\classes.py", line 9, in module
    selection.deposit
builtins.AttributeError: 'str' object has no attribute 'deposit'

5 个答案:

答案 0 :(得分:1)

如果仅用于演示目的,您可以在selection字典中查找locals()值:

In [4]: John = 1

In [5]: selection = "John"

In [6]: locals()[selection]
Out[6]: 1

所以,你的代码看起来像是:

class people(object):
    def deposit(self):
        print("depositing")
    def withdraw(self):
        print("withdrawing")
John = people()
selection = input("Type John: ")
locals()[selection].deposit()

但是,请不要在生产代码中使用此方法。有更好的模式可以将东西分派给对象..

答案 1 :(得分:0)

通常,您不希望用户输入和内部变量名之间存在这种直接对应关系。你有一些数据结构来跟踪你的people实例,也许是一个字典:

known_people = {'John': people(), 'Jake': people(), 'Jeffrey', people()}

并且您将处理用户输入以确定如何处理您的数据:

selected_person = known_people[selection]
selected_person.deposit()

虽然您在技术上可以动态访问变量:

John = people()
selected_person = locals()[selection]
你真的,真的不应该。它不能很好地扩展到更复杂的数据,它引入了许多令人讨厌的错误。

答案 2 :(得分:0)

<<<<<< answer is here<<>> and here>>>>>>

答案 3 :(得分:0)

您可以将人员(如约翰)存储在单独的对象(如字典)中。

考虑这种方法:

class Man(object):
    # I renamed the `people` class to `Man` since it's representing a single man (like John).
    # You also have to add a required `self` parameter for every function inside of the class!
    def deposit(self):
        print("depositing")

    def withdraw(self):
        print("withdrawing")

# We'll make `people` a dictionary instead.
people = {
    'John': Man()
}

selection = raw_input("Type John: ")

# You have to put parentheses there so the `deposit()` function would call
people[selection].deposit()

eval() is pretty evilso as locals()

答案 4 :(得分:-1)

input("Type John: ")返回一个字符串,而不是people类型的对象,因此您无法在其上调用方法deposit

解决方法 -

class people(object):
    def deposit(self):
        print("depositing")
    def withdraw(self):
        print("withdrawing")
selection = input("Type people(): ")
selection.deposit()

输入 -

people()  

<强>输出 -

depositing

Screenshot