简体   繁体   中英

How do i access a class through input

I put together a small test code just to demonstrate the error I am getting when trying to enter a class with input. Nothing pretty or good its just to get the specific error across.

Code:

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

Error:

[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'

If it's only for demonstration purposes you could lookup the selection value in the locals() dict:

In [4]: John = 1

In [5]: selection = "John"

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

So, your code would look like:

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

However, please do not use this approach in production code. There are better patterns for dispatching stuff to objects..

Generally, you don't want this kind of direct correspondence between user input and your internal variable names. You'd have some data structure to keep track of your people instances, perhaps a dict:

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

and you'd process user input to determine what to do with your data:

selected_person = known_people[selection]
selected_person.deposit()

While you technically can access variables dynamically:

John = people()
selected_person = locals()[selection]

you really, really shouldn't. It doesn't scale well to more complex data, and it introduces potential for lots of nasty bugs.

<<<<<< 答案在这里 << >> 和这里 >>>>>>

You could store the people (like John) in a separate object (like a dictionary).

Consider that approach:

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 evil , so as locals() .

input("Type John: ") returns a string, not an object of type people so you can't call the method deposit on it.

Workaround-

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

Input-

people()  

Output-

depositing

屏幕截图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM