python doesn't work, it should return "new user being created", but nothing works is it a bug?
class User:
def __int__(self):
print("new user being created...")
user_1 = User()
user_1.id = "001"
user_1.username = "angela"
print(user_1.username)
user_2 = User()
user_2.id = "002"
user_2.username = "jack"
i already tryed everything, why doesn't it print anything? in def int(self):
Related
First i created a class named 'employed' which looks like this-
class employed:
def __init__(self,name, age, salary, role):
self.name = name ; self.age = age
self.salary = salary ; self.role = role
def givedata(self):
return(f"name : {self.name}\nage : {self.age}\nsalary : {self.salary}\nrole : {self.role}")
Then, i created two class objects for this class-
saksham = employed("Saksham", 13, 10000, "developer")
rohan = employed("Rohan", 15, 12000, "team leader")
Now i want to take input from the user of which object's data he like to view. How can i do that?
First, we defined a function which returns the user who matches the name
if the function returns none means there is no user that name otherwise it will return user.
Before that, I've added all users into list for convineince
saksham = employed("Saksham", 13, 10000, "developer")
rohan = employed("Rohan", 15, 12000, "team leader")
objects = []
objects.append(saksham)
objects.append(rohan)
def view_object(name):
for user in objects:
if user.name == name:
return user;
name = input("Hey User... Who do you want to view: "
user = view_object(name)
if user is None:
print("Sorry there is no user with this name")
else:
print(str(user))
There is no switch case in python but you can implement it as follows
define these functions in class
def get_name(self):
return self.name
def get_salary(self):
return self.salary
then use the following method
def numbers_to_months(argument):
switcher = {
1: object.get_salary(),
2: object.get_name(),
}
# Get the function from switcher dictionary
func = switcher.get(argument, lambda: "Invalid month")
# Execute the function
print get_salary()
I am trying to create an object that creates user ID's from the input of user. I am learning OOP through this. I need help!!
I tried my best, I'M NEW
class creat:
def __init__(self, userid):
self.userid = userid
def enter(self, show):
print(userid)
self.show = show
userid = input("enter user id")
show = print(userid)
creat()
userid.enter()
My error is coming up as:
enter user id998
Traceback (most recent call last):
File "/Users/singlefawn/Desktop/Our Realm/1997/Programs/random gallery/_sooseow_1_0.py", line 14, in <module>
creat()
TypeError: __init__() missing 1 required positional argument: 'userid'
998
Process finished with exit code 1
You need to pass userid to Creat (classes should be UpperCaseStyle in python) when instantiating it, and then you need to properly call the enter method.
class Creat:
def __init__(self, userid):
self.userid = userid
self.show = None
def enter(self, show):
self.show = show
userid = input("enter user id: ")
some_user = Creat(userid) # instantiate Creat with userid
print("user id: {:s}".format(some_user.userid))
some_user.enter("some show info") # enter some show info
print("show: {:s}".format(some_user.show))
print("\nUser Info\nUser: {:s}\nShow: {:s}".format(some_user.userid,some_user.show))
You could also put the input inside the class init like this:
class Creat:
def __init__(self):
self.userid = input("enter user id: ") # ask for id here
self.show = None
def enter(self, show):
self.show = show
some_user = Creat() # instantiate Creat without userid
print("user id: {:s}".format(some_user.userid))
some_user.enter("some show info") # enter some show info
print("show: {:s}".format(some_user.show))
print("\nUser Info\nUser: {:s}\nShow: {:s}".format(some_user.userid,some_user.show))
Output:
enter user id: alice
user id: alice
show: some show info
User Info
User: alice
Show: some show info
To have the user input show you could do something like this:
class Creat:
def __init__(self):
self.userid = input("enter user id: ")
self.show = None
def enter(self, show):
self.show = input("what show do you like?: ")
some_user = Creat() # instantiate Creat with userid
print("user id: {:s}".format(some_user.userid))
some_user.enter("some show info") # enter some show info
print("show: {:s}".format(some_user.show))
print("\nUser Info\nUser: {:s}\nShow: {:s}".format(some_user.userid,some_user.show))
New Output:
enter user id: Alice
user id: Alice
what show do you like?: Bob Newhart
show: Bob Newhart
User Info
User: Alice
Show: Bob Newhart
you need to pass userid when instanciating your class creat, so you should do
creat(userid)
also when calling the enter method you should pass the show parameter
I try to write a ChatBot program that will respond to each user differently.
So I implement like this: When there is a new user, ask the bot to do something and my bot needs to ask user back for more information and wait for the response message, my code will register a dict with a key of user_id and value of call_back function of class User like example code below.
class User:
api_dict = {}
def __init__(self, user_id):
self.user_id = user_id
def ask_username(self,chat_env):
chat_env.send_msg(self.user_id,"Please enter your username")
api_dict[self.user_id] = self.ask_birth_date
def ask_birth_date(self,message,chat_env)
chat_env.send_msg(self.user_id,"Mr. {} what is your birth date".format(message))
# do some thing
def hook_function(user_id,message,chat_env)
if is_first_hook(user_id):
user = User(user_id)
user.ask_username()
else:
User.api_dict[user_id](message,chat_env)
But it was not working as python threw an error that it didn't receive chat_env parameter in ask_birth_date() in which I think self wasn't passed to the function.
So is there any way to make self still attach with ask_birth_date()?
I think that you must be storing all the instances of User somewhere to be able to call ask_username when a connection is first made. Therefore you can transform api_dict into a state pattern.
Users = {} # I'm guessing you already have this!
class User:
def __init__(self, user_id):
self.user_id = user_id
def ask_username(self, chat_env):
chat_env.send_msg(self.user_id, "Please enter your username")
self.current = self.ask_birth_date
def ask_next_question(self, message, chat_env)
self.current(message, chat_env)
def ask_birth_date(self, message, chat_env)
chat_env.send_msg(self.user_id, "Mr. {} what is your birth date".format(message))
self.current = self.record_birth_date # for example
# There must be code that does this already
def new_connection(user_id, chat_env):
Users[user_id] = User(user_id)
Users[user_id].ask_username(chat_env)
# I assume this is called for every message that arrives from a user
def hook_function(user_id, message, chat_env)
Users[user_id].ask_next_question(message, chat_env)
Update:
Your hook function doesn't call ask_username() properly. That is why you are getting the error. That is why you should post all your code and the whole of the stack trace!
This code should fix your call site:
def hook_function(user_id, message, chat_env)
if is_first_hook(user_id):
user = User(user_id)
user.ask_username(chat_env) # add param here!
# btw the user instance here is thrown away!
else:
User.api_dict[user_id](message, chat_env)
If the above fixes your problems, then that means that the User class is unnecessary. You could just have api_dict as a global and the methods can become free functions.
Your code can be reduced to this:
api_dict = {}
def ask_username(chat_env, user_id):
chat_env.send_msg(user_id, "Please enter your username")
api_dict[user_id] = ask_birth_date
def ask_birth_date(chat_env, user_id, message)
chat_env.send_msg(user_id, "Mr. {} what is your birth date".format(message))
# do some thing
def hook_function(user_id, message, chat_env)
if is_first_hook(user_id):
ask_username(chat_env, user_id)
else:
api_dict[user_id](chat_env, user_id, message)
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I am trying to incorporate a regex check for user input in my class. I want a scenario where users can't proceed to enter their name until they enter a valid email address. The current code i have isn't working as expected.
I suppose a while-loop is in order here but i am struggling to implement that in this class. Any assistance is much appreciated.
class test:
def __init__(self):
self.email = input("Enter your email: ")
email_check = re.search(r'[\w.-]+#[\w.-]+.\w+', self.email)
if email_check:
print ('email valid')
else:
print ('email not valid')
self.email = input("Enter your email: ")
sys.exit(0)
self.name = input("Enter your name: ")
You can do it like this.
while True:
self.email = input ("Enter email:")
if valid_email:
break
Substitute valid_email with your way of validating the email address.
You may also be interested in Python check for valid email address? for ways to validate an email address.
First of all - you should not implement any activity of this kind into __init__ method, as one is intended for object fields initialization first place. Consider dedicated 'check_email' method, or whatever name applies best.
Now, regarding your case:
class test:
def __init(self):
# whatever initialization applies
pass
def init_emails():
emails = []
proceed = True
# if you really in need of do/while loop
while proceed:
email = self.input_email()
# your logic for input
if email is not None:
emails.append(email)
# invalid input or cancel
else:
proceed = False
return input
def input_email(self):
value = input('Enter your email:')
# TODO: validate/check input
return proper_value
class test:
def __init__(self):
self.email = self.get_name()
def get_name(self) :
while True:
x = input("Enter your email: ")
if (re.search(r'[\w.-]+#[\w.-]+.\w+', x)) :
return x
This script functions as described, in the end printing the name and email. If you need to use python2.7, use raw_input instead of input. I used for i in range instead of while True to avoid an endless loop.
#!/usr/bin/env python3
import re
import sys
class Test(object):
def __init__(self):
self.email = None
self.name = None
def get_email(self):
for i in range(3):
email = input('Enter your email: ')
if re.search('[\w.-]+#[\w.-]+.\w+', email):
return email
print('Too many failed attempts!')
sys.exit(1)
def get_name(self):
for i in range(3):
name = input('Enter your name: ')
if name:
return name
print('Too many failed attempts!')
sys.exit(1)
def initialize(self):
self.email = self.get_email()
self.name = self.get_name()
print('"{}" <{}>'.format(self.name, self.email))
if __name__ == '__main__':
t = Test()
t.initialize()
Instead of input, try to use raw_input. Like this:
self.email = raw_input("Enter your email:")
There'll be no error anymore.
Hope this helps.
I am still learning OOP Design Pattern and everything I have read so far says that Factory Patterns are commonly used. I am still trying to learn this pattern. For my program I am creating an Abstract Factory called "person" and my factory called "personFactory" should let you create different types of people (Users, Customers, Plumbers, etc...). With my current code I am getting this error:
AttributeError: 'NoneType' object has no attribute 'fName'
This is my code:
person.py
import abc
class person:
__metaclass__ = abc.ABCMeta
fName = ""
mName = ""
lName = ""
address = ""
city = ""
state = ""
zipcode = ""
email = ""
phone = ""
dob = None
personFactory.py
from person import person
class personFactory(person):
def createUser(self):
uName = ""
password = ""
role = ""
def __init__(self,uName,password,role):
self.uName = uName
self.password = password
self.role = role
def login(uName,password):
if(uName == self.uName and password == self.password):
return "Logged In"
else:
return "Did not log in"
def logout():
return "Logout"
def createCustomer(self):
items = []
balace = 0
def __init__(self,balance):
self.balance = balance
def AddToCart(item):
self.items.append(item)
print("Item added")
def Order(items):
totalprice = 0
for item in items:
totalprice =+ item.price
return totalprice
def Pay(payment):
self.balance =- payment
return self.balance
main.py
import personFactory
class main():
pf = personFactory.personFactory()
user1 = pf.createUser()
user1.fName = "John"
user1.lName = "Smith"
user1.uName = "jSmith"
user1.password = "Jamestown"
customer1 = pf.createCustomer()
customer1.fName = "George"
customer1.lName = "Washington"
customer1.balance = 100
main()
I'm not sure why fName is a NoneType. What am I doing wrong? Any help would be greatly appreciated!
You have the constructor inside the create_user method. As Ignacio was saying the init function must be outside of the create_user function, in order for you to pass the name, pass and role to the person_factory object at creation.
Or alternatively you could pass all those value to the create_user method as arguments and leave the class constructor out of the work.
Could be something like this...
class personFactory(person):
def __init__(self,uName,password,role):
self.uName = uName
self.password = password
self.role = role
def createUser(self):
user = Person()
user.type = "user"
user.uName = self.uName
user.password = self.password
user.role = role
return user
Or...
class personFactory(person):
def createUser(self, uName, password, role):
user = Person()
user.type = "user"
user.uName = uName
user.password = password
user.role = role
return user
I would also suggest that you made use of inheritance and made concrete classes based on your abstract classes that represent each of your objects.
Like...
class User(Person):
def __init__(name, password, role):
self.name = name
self.type = "User"
self.password = password
So you can have a User class, and a Customer class, and each method of your factory can create the corresponding object, instead of a regular Person.