Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

python - Basic OOP - 'str' object has no attribute 'age'

I am trying to do some basic OOP commands, this code works when I directly put in the attribute name, but not when I try to get it from a user input

print('Hello, welcome')

class ManCity:

    def __init__(self, name, age, position):
        self.name = name
        self.age = age
        self.position = position

    def getName(self):
        print(self.name)

    def getAge(self):
        print(self.age)

    def getPosition(self):
        print(self.position)


aguero = ManCity('Sergio Aguero', 32, 'Striker')
sterling = ManCity('Raheem Sterling', 27, 'Winger')
jesus = ManCity('Gabriel Jesus', 24,'Striker')
dias = ManCity('Ruben Dias', 29, 'Centre Back')
stones = ManCity('John Stones', 26, 'Centre Back')
ederson = ManCity('Ederson', 29,'GoalKeeper')

chosenName = input(str('Choose Player'))
ManCity.getAge(chosenName)

question from:https://stackoverflow.com/questions/65891768/basic-oop-str-object-has-no-attribute-age

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to check the chosenName for each instance like

class ManCity:

    def __init__(self, name, age, position):
        self.name = name
        self.age = age
        self.position = position

    def getName(self):
        print(self.name)

    def getAge(self):
        print(self.age)

    def getPosition(self):
        print(self.position)


aguero = ManCity('Sergio Aguero', 32, 'Striker')
sterling = ManCity('Raheem Sterling', 27, 'Winger')
jesus = ManCity('Gabriel Jesus', 24,'Striker')
dias = ManCity('Ruben Dias', 29, 'Centre Back')
stones = ManCity('John Stones', 26, 'Centre Back')
ederson = ManCity('Ederson', 29,'GoalKeeper')

chosenName = input(str('Choose Player'))
# You can iterate over the created objects
for e in [aguero, sterling, jesus, dias, stones, ederson]:
    # for each object you will check if the name is same or not
    if(e.name == chosenName):
        print(e.getAge())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...