ok I'm trying to make a code to display a list of admin privileges. I made the code and things work but it gives me a weird display before any of the list items:
input code:
class Privileges:
def __init__(*privileges):
privileges
def show_privileges(*privileges):
print("these are your privileges:")
for privilege in privileges:
print(f"\t{privilege}")
class Admin(User):
def __init__(self, first_name, last_name, age, username):
super().__init__(first_name, last_name, age, username)
self.privileges = Privileges()
Admin = Admin('Admin', '', '' ,'')
Admin.privileges.show_privileges('can add post', 'can delete post',
'can ban user')
output:
these are your privileges:
<__main__.Privileges object at 0x7facd3c5f4f0>
can add post
can delete post
can ban user
The function show_privileges(*privileges) is being given self as the first argument. That is the weird output that you are seeing, self is being printed. You need to either include self in the definition as:
def show_privileges(self, *privileges):
print("these are your privileges:")
for privilege in privileges:
print(f"\t{privilege}")
Or you can slice the list to avoid the first element:
def show_privileges(*privileges):
print("these are your privileges:")
for privilege in privileges[1:]:
print(f"\t{privilege}")
The first option would be more typical i think.
To read more about self and how it works in python you can read the tutorial mentioned by codewelldev.
Related
I am trying to have the ability to mass create user accounts from a file that I upload in Python. So instead of creating users one at a time I can be giving a list of X amount of users and quickly create them. So for instance if I have a file(newusers.csv) that contains the usernames below how would I go about easily doing this?
First name, Last name, Username.
tom cat tcat11
Jerry Mouse Jmouse21
Mini Mouse Mmouse
Below is the code I have which is supposed to create the users:
def user_account():
userInformation = readFile("newusers.csv")
try:
subprocess.run(['useradd','-p', userInformation[1:]])
except:
print(f"failed to add user.")
sys.exit(1)
I don't know what specific options etc. you want in your useradd command so that i'm leaving out of this. However regarding the approach: This is one way you could approach it by creating a User class.
import csv
class User:
def __init__(self, firstname, lastname, username):
self.firstname = firstname
self.lastname = lastname
self.username = username
def save(self):
try:
# WHATEVER COMMAND AND OPTIONS YOU ARE LOOKING TO RUN
# USING self.username, ETC. AS ARGS
except:
print("failed to add user")
sys.exit(1) # if you don't want to attempt any of the other users
#staticmethod
def mass_save(users):
for user in users:
user.save()
#staticmethod
def read_users_from_file(file_path):
with open(file_path, "rt") as f:
users = csv.reader(f)
next(users) # Skip header row
return [User(*row) for row in users] # Unpack each userinfo row from csv upon instantiation
if __name__ == "__main__":
users = User.read_users_from_file("users.csv")
User.mass_save(users)
I created a class whose parameters are user inputs and the attributes are saved as a dictionary into a file with json, to be re-read by python. Now, I want to be able to access the information in that file(the "username" attribute) from a separate file. If the username matches, then you successfully log in.
File Name: create_user_dataset
"""THIS PROGRAM CREATES A USER AND SIMPLY STORES ITS INFO IN A TXT FILE TO BE RE-READ BY PYTHON"""
from pip._vendor.distlib.compat import raw_input
import json
class User():
'''simulates a user for a social network or pc'''
def __init__(self, first_name, last_name, username, location, *interests):
'''initialize attributes of user class'''
self.first_name = first_name.title()
self.last_name = last_name.title()
self.username = username
self.location = location.title()
self.interests = interests
#classmethod
def get_userinfo(cls):
'''creates a variable to store user inputs that correspond to User attributes'''
first = raw_input("Welcome. PLease Enter Your First Name: ")
last = raw_input("Please Enter Your Last Name: ")
user = raw_input("Username: ")
location = raw_input("What is your location? : ")
interests = []
print("List some of your interests (Press 'Q' Key to End Program.)")
active = True
while active:
'''infinite loop that creates elements in a list until user quits'''
interest = input().strip()
if interest == 'q':
active = False
else:
interests.append(interest)
print("Press 'Q' Key to End Program.")
return cls(first, last, user, location, interests)
"""cls fills in the attributes that would go inside of a given User instance"""
def to_json(self):
return json.dumps({"first": self.first_name, "last": self.last_name, "username": self.username,
"location": self.location, "interests": self.interests})
#classmethod
def from_json(cls, j):
dct = json.loads(j)
return cls(dct["first"], dct["last"], dct["username"], dct["location"], dct["interests"])
The second file simply creates instances of User:
File Name: create_user_frontend
"""THIS PROGRAM CREATES INSTANCES OF USER AND STORES THEIR INFO IN A FILE"""
from create_user_dataset import User
def create(user):
'''creates an instance of User object'''
filename = r'''C:\Users\User\Documents\dataset1.txt'''
with open(filename, 'r+') as f:
'''writes each attribute of User into a file'''
f.write(user.get_userinfo().to_json())
user1 = User
create(user1)
All of the previous works perfectly, I just wanted to provide background. The third file is the problem. The problem is that when I create a new file, while importing the file where my instance of User is stored, console just runs the imported file rather than the file itself.
File Name: user_login
import create_user_frontend as cu
prompt_username = input("Please enter username: ")
print(cu.user1)
This code in create_user_frontend.py will be executed at the time it is imported:
user1 = User
create(user1)
If you don't want it to be executed when it is imported, but only if the file itself is run (e.g. by calling python create_user_frontend.py) you should change it to this:
if __name__ == "__main__:
user1 = User
create(user1)
BTW, this won't fix all of your problems, only the one you asked about.
You still have many problem to handle:
after this change, cu.user1 is no longer available
on the other hand cu.user1 is actually nothing else but create_user_dataset.User, because of the dubious line user1 = User
function create(user) just receives he User class, so it is pointless for it to receive anything
you probably want to call User.get_userinfo() to actually create a user instance
you should definitely either change the names of these functions, or their functionality, because the names don't match what they do:
User.get_userinfo does not get user info - it creates a User instance
create(user) neither takes a user instance as argument, nor does it return a new user - it creates a user instance, dumps its contents into json and then throws away the instance in the same line
I am trying to call a function on button click using flask. Here is a snippet of my code to make my question clearer.
class User:
def __init__(self, username):
self.username = username
def find(self):
user = graph.find_one("User", "username", self.username)
return user
def add_restaurant(self, name, cuisine, location):
user=self.find()
restaurant = Node("Restaurant", id=str(uuid.uuid4()),name=name)
graph.create(restaurant)
graph.create(rel(user,"LIKES", restaurant))
rest_type = Node("Cuisine", cuisine=cuisine)
graph.create(rest_type)
graph.create(rel(restaurant,"SERVES", rest_type))
loc = Node("Location", location=location)
graph.create(loc)
graph.create(rel(restaurant, "IN", loc))
The add_restaurant function is supposed to create 3 nodes and their corresponding relationships in Neo4j graph database, and it works fine.
But, when I call this function from my Flask file, I get an
AttributeError: User instance has no attribute 'add_restaurant'
This is the function in the Flask file
#app.route('/add_restaurant', methods=['POST'])
def add_restaurant():
name = request.form['name1']
cuisine = request.form['cuisine1']
location = request.form['location1']
username = session.get('username')
if not name or not cuisine or not location:
if not name:
flash('You must enter a restaurant name')
if not cuisine:
flash('What cuisine does the restaurant belong to')
if not location:
flash('You must enter a location')
else:
User(username).add_restaurant(name, cuisine, location) #Error comes from here.
return redirect(url_for('index'))
name, cuisine, and location are generated from text fields. What am I doing wrong to get this error?
I looked into this thanks to some similar questions here on stack overflow. I think when you create the user instance with
User(username).add_restaurant(name, cuisine, location)
The user is not properly instantiated. Try with:
else:
user = user(username)
user.add_restaurant(name, cuisine, location)
Let us know if this is of any help.
Right, so I'm trying to create a Contacts application using Python OOP. I'm fairly new to OOP and still trying to get my head around the concepts.
I understand that a Class is a blueprint for all objects. I like to think of a Class as an entity and each Object is a record of that entity. I am from a Database background so that's why I interpret it like this, feel free to correct me.
Anyways, in the Contacts app I'm making I've created the Class Contacts as outlined below:
class Contacts():
def __init__(self, firstName, lastName, address, groupType,
telephone, mobile, email, photoField):
self.firstName = firstName
self.lastName = lastName
self.address = address
self.groupType = groupType
self.telephone = telephone
self.mobile = mobile
self.email = email
self.photoField = photoField
def showDetails(self):
print("First Name:\t", self.firstName)
print("Last Name:\t", self.lastName)
print("Address:\t", self.address)
print("Telephone:\t", self.telephone)
print("Mobile:\t", self.mobile)
print("Email:\t", self.email)
Now, if I want to add contacts through the Contacts class into the list I'm using to store each contact object, do I have to create an AddContacts class, or do I create a function instead? I don't know if I'm putting my question across well enough for you to understand what I mean?
What I guess I'm trying to say is that adding contacts is a process and if you look at it from a database point of view you wouldn't create a table called "tbl_AddContacts" since you would do that via a query or a stored procedure, so in my view I would define adding contacts being a function. But asking my colleague who does C# programming he says that adding contacts should be defined by a Class.
This is a confusing concept for me, especially since I don't understand how I would link the AddContacts class with the Contacts class, or even how to define an AddContacts class in the first place!.
Here is the function I defined for adding contacts:
def addContacts():
firstName = input("First Name: ")
lastName = input("Last Name: ")
address = input("Address: ")
telephone = input("Telephone: ")
mobile = input("Mobile: ")
email = input("Email: ")
print("\n")
contact = Contacts(firstName, lastName, address, None, telephone, mobile, email, None)
contactsList.append(contact)
pickle.dump(contactsList, open("save.p", "wb"))
Please help me out, since I will turning this into a GUI application (uni assignment).
Adding a contact is doing something, rather than being something, so it would make sense as a method/function rather than a class. I would suggest that your functionality should actually be in two separate places.
Creating a new contact from user input should be a class method of Contact:
class Contact(object):
...
#classmethod
def from_input(cls):
firstName = input("First Name: ")
lastName = input("Last Name: ")
address = input("Address: ")
telephone = input("Telephone: ")
mobile = input("Mobile: ")
email = input("Email: ")
return cls(firstName, lastName, address, None,
telephone, mobile, email, None)
Adding a new contact to the list of contacts should either be:
An instance method of the e.g. AddressBook or ContactList class (or whatever you have holding the contact list); or
A separate function if you don't have a class to hold the Contact instances.
For example:
class AddressBook(object):
...
def add_contact(self, contact=None):
if contact is None:
contact = Contact.from_input()
self.contacts.append(contact)
Now your UI can create a Contact and pass it straight to address_book.add_contact().
First, your Contacts class is more appropriately called Contact, since it only represents a single contact. Your addContacts options can either be a standalone function, or you could make it part of a ContactList class, which manages your list of Contact objects.
class ContactList():
def __int__(self):
self.contact_list = []
def addContact(firstName, lastName, address, telephone, mobile, email):
contact = Contact(firstName, lastName, address, None, telephone, mobile, email, None)
self.contact_list.append(contact)
pickle.dump(contact_list, open("save.p", "wb"))
I would recommend separating the UI interaction piece (all the input() calls) from your function/method, because as you said, eventually this is going to become a GUI app. You should keep the code that's actually getting input from the user separated so you can change it later without having to change any part of Contact or ContactList.
Let's say Bob enters his name, 'Bob Jones,' into a Tkinter text entry field. Later, I want to be able to access his name like this:
BobJones = {
'name':'Bob Jones',
'pet\'s name':'Fido'
}
How do I make it so I assign whatever Bob inputs as a new variable without having to manually write it in?
Thanks in advance.
To expand on the comments above, I think you'd want something more like this:
# Define the user class - what data do we store about users:
class User(object):
def __init__(self, user_name, first_pet):
self.user_name = user_name
self.first_pet = first_pet
# Now gather the actual list of users
users = []
while someCondition:
user_name, first_pet = getUserDetails()
users.append(User(user_name, first_pet))
# Now we can use it
print "The first users name is:"
print users[0].user_name
So you're defining the class (think of it as a template) for the Users, then creating new User objects, one for each person, and storing them in the users list.