简体   繁体   中英

Python - Input and OOP

if I want to use input as Variables name in OOP and Classes how should i do it:

class animal:
    def  __init__(self,name,age):
        self.name = name
        self.age = age
    def display_age(self):
        print("{} Age: {}".format(self.name,self.age))

def create():
    name = input("enter name: ")
    age = input("enter age: ")
    name = animal(name,age)

create()
Ben.display_age()

output:

enter name: Ben

enter age: 12

NameError: name 'Almog' is not defined

Here's a function that does something similar. We will store Animal objects inside a dictionary, using the name of each object as its key.

class Animal:
    def  __init__(self,name,age):
        self.name = name
        self.age = age
    def display_age(self):
        print("{} Age: {}".format(self.name,self.age))

def create(storage):
    name = input("enter name: ")
    age = input("enter age: ")
    storage[name] = Animal(name,age)

storage = {}
create(storage)
storage['Ben'].display_age() # If you didn't use Ben as the name, this will fail with a KeyError

Hope this helps. Here you need to use the object which has been created.

class Animal:
    def  __init__(self,name,age):
        self.name = name
        self.age = age

    def display_age(self):
        print("{} Age: {}".format(self.name,self.age))

def create():
    name = raw_input("enter name: ")
    age = input("enter age: ")
    return Animal(name, age)

a = create()
a.display_age()

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