Python AttributeError:- Main instance has no attribute 'placeName' - python

class Main():
def __init__(self):
def placeName(self):
place_name = raw_input("\n=> Enter a place name: ")
placename_data = place_name.strip()
if re.match("^[a-zA-Z]*$", placename_data):
return placename_data
else:
print("Error! Only Alphabets from are allowed as input!")
a = Main()
new = a.placeName()
Above code for placeName() method runs correctly without using class but when I try to add it in a class, code gives an attribute error . Can't understand what is wrong here.

You don't need to define __init__ inside the Main class.
class Main():
def placeName(self):
place_name = raw_input("\n=> Enter a place name: ")
placename_data = place_name.strip()
if re.match("^[a-zA-Z]*$", placename_data):
return placename_data
else:
print("Error! Only Alphabets from are allowed as input!")
a = Main()
new = a.placeName()
Please remove __init__ method and try.

Related

How to use variable from constructor inside of methode?

Hi guys hope u are doing well, i'm new with python :)
so i have two issues the first how can i use the variable name from the init to my function game() which it use two args (those args whose make it realy difficult for me !) as u can see in code bellow:
# FUNCTION.py
class penGame():
def __init__(self):
print("Welcome to Pendu Game")
self.name = input("Enter your name: ") # IMPORT THIS VARIABLE FROM HERE
def game(self, letter, rword):
letter = letter.lower()
if letter in rword:
for Id, Value in enumerate(rword):
if Value == letter:
donnee.default_liste[Id] = letter
else:
name2 = self.name # it deosn't work i got 1 missing arg when i run the code from MAIN.py
print(f"try again {name} it's wrong ")
print("-".join(donnee.default_liste))
The second issue is i need to use the same variable (name) from init in another module which is my main module and i couldn't use it cause i tried to create an object from class penGame() like:
myObject = penGame()
name2 = myObject.name
then use the name2 inside of the if condition as u can see bellow but it doesn't work properly cause it run the init again which is not what i want actualy !
any idea how can i did it plz?
#MAIN.py
import donnee
from fonctions import penGame
random_word = random.choice(donnee.liste_words) # creation of random word from liste_words
penGame() #call the constructor
while donnee.counter < donnee.score:
letter = input("Enter the letter: ")
if penGame.check(letter):
print("You cant use more one letter or numbers, try again !")
else:
penGame.game(letter, random_word) # as u can see that's the reason cause i supposed to send 3 args instead of two ! but i only need those two !!?
if penGame.check_liste():
myObject = penGame() # that's cause runing the init everytime !!
name2 = myObject.name
print(f"congratulation {name2} you've guessed the word, your score is: {donnee.choice-donnee.counter} point.")
break
if penGame.loser():
print(f"the word was {random_word.upper()} you have done your chances good luck next time.")
donnee.counter += 1
Thank u in advance hope u help me with that and excuse my english if it wasn't that good :) :)
1.Error
You're calling the methods on the class penGame, not on a instance of penGame.
This causes your missing argument error because the method needs an instance of the class (the self parameter) but don't get one.
Instead use your variable (from the second solution):
if mygame.check(letter):
print("You cant use more one letter or numbers, try again !")
else:
mygame.game(letter, random_word)
...
Replace penGame with mygame also in the other calls.
Error
Save the result of the call in a variable and you won't need to recreate it.
mygame = penGame() # call the constructor
This line can then be removed:
myObject = penGame() # that causes the init to run again because it creates a new instance!

Menu Function and Classes in Python

class Character:
def __init__(self, name,):
self.name = name
def help (self):
print (menu.keys())
def name(self):
print ("Hast du schon vergessen ? ")
c = Character
c.name = input("Wie heißt du denn ? ")
print ("Help, wenn du Hilfe brauchst")
menu ={"help":Character.help,
"name":Character.name}
#This function allows you call up the main menu at any point in the game.
while True :
line = input(">")
args = line.split()
if len(args) < 4:
Befehl_vorhanden = False
for c in menu.keys():
if args[0] == c[:len(args[0])]:
menu[c](c)
Befehl_vorhanden = True
break
if not Befehl_vorhanden:
print ("ich verstehe dich nicht.")
Thanks to the help of the other stack overflow users, I was able to get my code running. I have created a menu for my game that can be called up at any point. However, it won't allow me to print any text. If I input "name" for example, it gives me.
TypeError: 'str' object is not callable
I have even tried using it as a basic function without my menu. However, I can't seem to get this code to work.
Any suggestions would be greatly appreciated.
Thanks in advance,
Chris
Your line:
c.name = input("Wie heißt du denn ? ")
assigns the method Character.name to a string, hence you get 'str' object not callable on the line menu[c](c) because menu[c] is Character.name.
Update:
This program may be closer to the one you are looking for:
class Character:
def __init__(self, name):
self.namen = name
def help (self):
print (menu.keys())
def name(self):
print ("Hast du schon vergessen ? ", self.namen)
c = Character(input("Wie heißt du denn ? "))
print ("Help, wenn du Hilfe brauchst")
menu ={"help":c.help,
"name":c.name}
#This function allows you call up the main menu at any point in the game.
while True :
line = input(">")
args = line.split()
if len(args) < 4:
if args[0] in menu:
k = args[0]
menu[k]()
else:
print ("ich verstehe dich nicht.")
Note how I changed __init__() to perform: self.namen = name since your version also overwrites the declaration of def name(self):.

Beginner Python Classes - changing the attribute value with user input

I am just learning classes in Python and for the past day I am stuck with the below.
I am trying to use a user input (from the main() function) to change the value of an attribute in the class.
I have been throught the #property and #name.setter methods that allow you to change the value of a private attribute.
However I am trying to find out how you can use user input to change the value of an attribute that is not private.
I came up with the below but it does not seem to work. The value of the attribute remains the same after I run the program. Would you have any ideas why?
class Person(object):
def __init__(self, loud, choice = ""):
self.loud = loud
self.choice = choice
def userinput(self):
self.choice = input("Choose what you want: ")
return self.choice
def choiceimpl(self):
self.loud == self.choice
def main():
john = Person(loud = 100)
while True:
john.userinput()
john.choiceimpl()
print(john.choice)
print(john.loud)
main()
In choiceimpl you are using == where you should use =.
Like stated before, you are using a comparison with == instead of the =.
Also you are returning self.choice in userinput as a return value, but never use it, because you set self.choice equal to input.
Shorter example:
class Person:
def __init__(self, loud):
self.loud = loud
def set_loud(self):
self.loud = input("Choose what you want: ")
def main():
john = Person(100)
while True:
john.set_loud()
print(john.loud)
main()
1) Change: '=='(comparison operator) to '='(to assign)
2) Inside class:
def choiceimpl(self,userInp):
self.loud = self.userInp
3) Outside class
personA = Person(loud) # Create object
userInp = raw_input("Choose what you want: ") # Get user input
personA.choiceimpl(userInp) # Call object method

Using Input in User Defined Functions!(Python)

I am wondering, is there a way to use the input() function inside a user-defined function? I tried doing this
def nameEdit(name):
name = input()
name = name.capitalize
return name
Using input is fine. However, you aren't calling name.capitalize; you're just getting a reference to the method and assigning that to name. [Further, as pointed out by Bob, your function doesn't need a name argument.] The correct code would be
def nameEdit():
name = input()
name = name.capitalize()
return name
or more simply:
def nameEdit():
return input().capitalize()
Are you talking about asking for input from a user from a method? If so then this would be what you're looking for:
def nameEdit():
name = input("Enter your name: ")
name = name.capitalize()
return name

How do I catch NameError in Python?

I've been trying to write a simple program in python to use classes and test attributes. It asks the user to input one of the names, and uses that input to display 2 attributes of the name. I've tried to include a try...except block to catch the NameError that occurs when typing something that hasn't been defined as the name of an object, but I still get this traceback:
Traceback (most recent call last):
File "C:/Users/Bede/Documents/Technology/Programming/Python/276/testcode", line 18, in <module>
animalName = input(">")
File "<string>", line 1, in <module>
NameError: name 'Marmadukke' is not defined
I'm aware this probably isn't the best way to do things, so I'm open to all suggestions.
My full code is here:
class Dog(object):
def __init__(self,name,chasesCats):
self.name = name
self.chasesCats = chasesCats
class Cat(object):
def __init__(self,name,chasesMice):
self.name = name
self.chasesMice = chasesMice
Marmaduke = Cat("Marmaduke",True)
Timmy = Cat("Timmy",False)
Cerberus = Dog("Cerberus",True)
Max = Dog("Max",False)
print("Enter Marmaduke, Timmy, Max or Cerberus.")
animalName = input(">")
while 1:
try:
if isinstance(animalName,Cat):
print("Cat")
if animalName.chasesMice:
print("Chases mice")
else: print("Doesn't chase mice")
if isinstance(animalName,Dog):
print("Dog")
if animalName.chasesCats:
print("Chases cats")
else: print("Doesn't chase cats")
break
except NameError:
print("Try again!")
I'm guessing you're using python2.x. In that case, you should use raw_input instead of input. The problem is that on python2.x, input calls eval on the data you put in. I suppose, this means that you could put in the data as "Marmaduke" (note the quotes). But having the program behave differently depending on whether you're using python2.x or 3.x seems undesirable.
An easy way to make the code work for both, python2.x and python3.x:
try:
raw_input
except NameError:
raw_input = input
animalName = input(">") is outside of the try block. So the Error won't be caught.
Probably you want that inside the try block in the loop:
while 1:
try:
animalName = input(">")
if isinstance(animalName,Cat):
This line is the culprit:
animalName = input(">")
When you enter Marmadukke, which isn't defined yet, you get the name error, since you're trying to do:
animalName = Marmadukke #Not defined.
Wrap it in a try/except block:
try:
animalName = input(">")
except:
print("Invalid input!")
But to achieve this, it would be much better to store your animals to a dictionary, and retrieve only the name:
animals = {}
animals['Marmaduke'] = Cat("Marmaduke",True)
animals['Timmy'] = Cat("Timmy",False)
animals['Cerberus'] = Dog("Cerberus",True)
animals['Max'] = Dog("Max",False)
And to retrieve:
animalName = animals[raw_input(">")]
You can then put it inside your while function, and catch KeyError instead of NameError.
Hope this helps!
For the fun and interest, I have extended your code; try tracing through it, you should learn lots ;-)
class Mammal(object):
index = {}
def __init__(self, name, chases_what=type(None)):
Mammal.index[name] = self
self.name = name
self.chases_what = chases_what
def speak(self):
pass
def chase(self, who):
if isinstance(who, self.chases_what):
self.speak()
print('{} chases {} the {}'.format(self.name, who.name, who.__class__.__name__))
who.speak()
else:
print("{} won't chase a {}".format(self.name, who.__class__.__name__))
class Mouse(Mammal):
def speak(self):
print('Squeak! Squeak!')
class Cat(Mammal):
def __init__(self, name, chases=True):
super(Cat, self).__init__(name, Mouse)
self.chases = chases
def chase(self, who):
if self.chases:
super(Cat, self).chase(who)
else:
print("{} won't chase anything".format(self.name))
class Dog(Mammal):
def __init__(self, name, chases_what=Cat):
super(Dog, self).__init__(name, chases_what)
def speak(self):
print('Bark! Bark!')
def chase(self, who):
if self is who:
print("{} chases his own tail".format(self.name))
else:
super(Dog, self).chase(who)
# create animal instances
Mouse('Jerry')
Mouse('Speedy Gonzalez')
Cat('Garfield', chases=False)
Cat('Tom')
Dog('Max')
Dog('Marmaduke', (Cat, Mouse))
def main():
while True:
name = raw_input('Enter an animal name (or Enter to quit): ').strip()
if not name:
break
me = Mammal.index.get(name, None)
if me is None:
print("I don't know {}; try again!".format(name))
continue
chase = raw_input('Enter who they should chase: ').strip()
target = Mammal.index.get(chase, None)
if target is None:
print("I don't know {}".format(name))
else:
me.chase(target)
if __name__=="__main__":
main()

Categories