attributeError: 'list' object has no attribute..... - python

I am getting attributeError, but I don't understand....
class User():
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
self.login_attempt = 0
class Admin(User):
def __init__(self, first, last, age):
super().__init__(first, last, age)
self.privilages = Privilages()
class Privilages():
def __init__(self, privilages = ''):
self.privilages = []
def show_privilages(self):
print("There are the privilages... : ")
if self.privilages:
for privilage in self.privilages:
print("- " + privilage)
else:
print("The user has no privilages. ")
sarah.privilages = ['can add post', 'can delete post']
sarah.privilages.show_privilages()
I am not sure what I am missing here, I used for loops to go over the list and print it out, however I keep getting error of "'list' object has no attribute 'show_privileges'"

You're assigning a list to sarah.privilages, so it surely does not have a show_privilages method. You should make the __init__ method of Admin take a list of privileges as a parameter, so it can pass on to the __init__ method of Privilages to initialize its privilages attribute:
class Admin(User):
def __init__(self, first, last, age, privilages):
super().__init__(first, last, age)
self.privilages = Privilages(privilages)
class Privilages():
def __init__(self, privilages):
self.privilages = privilages
def show_privilages(self):
print("There are the privilages... : ")
if self.privilages:
for privilage in self.privilages:
print("- " + privilage)
else:
print("The user has no privilages. ")
sarah = Admin('sarah','mary','smith', ['can add post', 'can delete post'])
sarah.privilages.show_privilages()
This outputs:
There are the privilages... :
- can add post
- can delete post

Write a separate Privileges class. The class should have one
attribute, privileges, that stores a list of strings.
Move the show_privileges() method to this class. Make a Privileges instance
as an attribute in the Admin class. Create a new instance of Admin and use your
method to show its privileges
class User():
"""Represent a simple user profile."""
def __init__(self, first_name, last_name, username, email, location):
"""Initialize the user."""
self.first_name = first_name.title()
self.last_name = last_name.title()
self.username = username
self.email = email
self.location = location.title()
class Admin(User):
def __init__(self, first_name, last_name, username, email, location):
super().__init__(first_name, last_name, username, email, location)
#Initialize an empty set of privileges.
self.privileges= Privileges()
class Privileges():
def __init__(self,privileges =[]):
self.privileges = privileges
def Show_privileges(self):
print("\nPrivileges: ")
if self.privileges:
for privilege in self.privileges:
print("- " + str(privilege))
else:
print("- this user has no privileges.")
eric = Admin('suraj', 'boi', 'e_mater', 'e_matthes100#example.com', 'alaska')
eric.describe_user()
eric.privileges.Show_privileges()
print("\nAdding privileges...")
eric_privileges = [
'can reset passwords',
'can moderate discussions',
'can suspend accounts',
]
eric.privileges.privileges = eric_privileges
eric.privileges.Show_privileges()

Related

Class object does not update empty list

I'm trying to solve this problem on my own. The problem asks to write a class for employee information, then ask user to input that information, and finally print the entered information.
I want to use two for loops, one for getting information and one for printing the information. Unfortunately, the printing for loop does not working.
class Employee:
def __init__(self, name, id_num, department, job):
self.__name = name
self.__id_num = id_num
self.__department = department
self.__job = job
# setters
def set_name(self,name):
self.__name = name
def set_id(self,id_num):
self.__id_num = id_num
def set_department(self,department):
self.__department = department
def set_job(self,job):
self.__job = job
# getters
def get_name(self):
return self.__name
def get_id(self):
return self.__id_num
def get_department(self):
return self.__department
def get_job(self):
return self.__job
def main():
employee_list = []
for i in range(2):
name = input('What is the name of the employee? ')
id_num = float(input('What is the ID number of the employee? '))
department = input('What is the department where the employee works? ')
job = input('What is the job title of the empoyee? ')
personnel = Employee(name,id_num,department,job)
employee_list.append(personnel)
return employee_list
for item in employee_list:
print(item.get_name())
print(item.get_id())
print(item.get_department())
print(item.get_job())
print()
main()
You need to remove the following line in your main() function:
return employee_list
It is causing your main to stop running without ever reaching the printing for loop.

I want to make a class attribute into a tuple that receives its input through raw user inputs and saves the results into a file

The following code works fine. But I want to make some modifications.
from pip._vendor.distlib.compat import raw_input
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):
'''each attribute of User is defined by a user input'''
return cls(
raw_input("Welcome. PLease Enter Your First Name: "),
raw_input("Please Enter Your Last Name: "),
raw_input("Username: "),
raw_input("What is your location? : "),
raw_input("List some of your interests: ")
)
def __str__(self):
'''returns all attributes of User as strings'''
return str("User: " + self.first_name + self.last_name +
"\nUsername: " + self.username +
"\nLocation: " + self.location +
"\nInterests: " + self.interests)
'''creates an instance of User object'''
user1 = User.get_userinfo()
'''writes each attribute of User into a file'''
filename = r'''C:\Users\User\Documents\dataset1.txt'''
with open(filename, 'r+') as file_object:
contents = file_object.write(str(user1))
I want to make the parameter 'interests' into a tuple or a list. The user should be able to input many interests and decide when to stop through a flag such as 'active = True', and then finally return the results as a string to be able to write it to the file.
Sorry, I don't follow the flag part. But is this what you had in mind? You stop by just entering your items. * I will update if I misunderstood
$ vi test.txt
$ python test.txt
from pip._vendor.distlib.compat import raw_input
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.split(', ')
#classmethod
def get_userinfo(cls):
'''each attribute of User is defined by a user input'''
return cls(
raw_input("Welcome. PLease Enter Your First Name: "),
raw_input("Please Enter Your Last Name: "),
raw_input("Username: "),
raw_input("What is your location? : "),
raw_input("List some of your interests: ")
)
def __str__(self):
'''returns all attributes of User as strings'''
return "User: {0} {1} \nUsername: {2} \nLocation: {3} \nInterests: {4}".format(self.first_name, self.last_name, self.username, self.location, ','.join(self.interests))
'''creates an instance of User object'''
user1 = User.get_userinfo()
print(user1)
$ python test.txt
Welcome. PLease Enter Your First Name: Hi
Please Enter Your Last Name: How
Username: Are
What is your location? : You
List some of your interests: Ball, Tennis, Python
User: Hi How
Username: Are
Location: You
Interests: Ball, Tennis, Python
I want to make the parameter 'interests' into a tuple or a list. The user should be able to input many interests and decide when to stop through a flag such as 'active = True'
I'm not sure how the user is going to set active=True, but the rest of that sentence just screams "I want a loop":
#classmethod
def get_userinfo(cls):
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 (just type Return on its own when you're done)")
while True:
interest = raw_input().strip()
if not interest:
break
interests.append(interest)
OK, that gives us a list, not a tuple. We could create a tuple by doing interests = interests + (interest,), but that's clunky and inefficient. If you really need a tuple, it's actually simpler to just build a list and then convert it at the end:
interests = tuple(interests)
And now we can pass all of those variables to the constructor:
return cls(first, last, user, location, interests)
… and then finally return the results as a string to be able to write it to the file.
Hold on; what kind of file are you creating here?
If this file is mean to be read and edited by a human being, and never looked at by Python again, that's easy. You can, e.g., just join them up with spaces, or commas, or newlines, or whatever you want. Or you can manually loop over them to format them more fancily:
def write_to_file(self, filename):
with open(filename, 'w') as file:
file.write('First Name: {}\n'.format(self.first_name))
file.write('Last Name: {}\n'.format(self.last_name))
file.write('Username: {}\n'.format(self.username))
file.write('Location: {}\n'.format(self.location))
file.write('Interests:\n')
for interest in self.interests:
file.write(' {}\n'.format(interest))
But if it's meant to be used for storing data to be read later by Python, you want to write things in a format that's meant to be parsed. Maybe add a method to serialize your objects to and from JSON, for example:
def to_json(self):
return json.dumps({'first': self.first_name, 'last': self.last_name,
'user': 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['user'],
dct['location'], dct['interests'])
And now, to write it to a file:
with open(filename, 'w') as f:
f.write(user.to_json())

__init__() missing 1 required positional argument (Python3) [duplicate]

This question already has answers here:
__init__() missing 1 required positional argument
(6 answers)
Closed 4 years ago.
during my python learning I've got an error in this code:
class User:
def __init__(self, first_name, last_name, location, payment_method):
self.first_name = first_name
self.last_name = last_name
self.location = location
self.payment_method = payment_method
self.login_attempts = 0
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
def printing_login_attempts(self):
print('Quantity of login attempts: ' + str(self.login_attempts))
def describe_user(self):
print('Current user first name: ' + self.first_name.title())
print('Current user last name: ' + self.last_name.title())
print('Location is ' + self.location.title() + '. Payment method is ' + self.payment_method)
def greet_user(self):
print('Hello ' + self.first_name.title() + ' ' + self.last_name.title() + '!!!')
class Admin(User):
def __init__(self, first_name, last_name, location, payment_method):
super().__init__(first_name, last_name, location, payment_method)
self.privilegis = Privilegis()
class Privilegis:
def __init__(self, privilegis_type):
self.privilegis_type = ['Allow to delete users', 'Allow to rename users', 'Allow to ban users']
def show_privilegis(self):
print('Special admins privilegis are: ' + ', '.join(self.privilegis))
new_user = Admin('John', 'Edwards', 'LA', 'visa')
new_user.privilegis.show_privilegis()
error description
self.privilegis = Privilegis()
TypeError: __init__() missing 1 required positional argument: 'privilegis_type'
I cant get what the problem is. How should I use one class(Privilegis) as attribute of another(Admin) ?
In your Privileges class, you write:
class Privileges:
def __init__(self, privilegis_type):
self.privilegis_type = ['Allow to delete users', 'Allow to rename users', 'Allow to ban users']
# ...
You thus specify that it requires a privilegis_type parameter, but that is strange, since later, you do nothing with that.
Either you should probably rewrite the constructor, and handle the parameter (and thus provide one when you construct a Privilegis object, or you should get rid of the parameter.
Your Admin class has a privilegis attribute that initializes an instance of Privilegis. The __init__() method defines how you initialize the class, and in your case it requires a privilegis_type as a parameter.
If you want this privilege to pass to the Admin at instantiation time, add the parameter to its __init__ method and pass that internally to the privilege attribute.
class Admin(User):
def __init__(self, first_name, last_name, location, payment_method, privilegis_type): # add privilegis type
super().__init__(first_name, last_name, location, payment_method)
self.privilegis = Privilegis(privilegis_type) # pass that privilegis type, needed by the Privilegis class
class Privilegis:
def __init__(self, privilegis_type):
self.privilegis_type = ['Allow to delete users', 'Allow to rename users', 'Allow to ban users']
def show_privilegis(self):
print('Special admins privilegis are: ' + ', '.join(self.privilegis_type)) # fixed that also
although in your code there are two major errors:
the Privilegis class is not using the parameter at all. You could maintain your original code, and remove the privilegis_type or use a sane default, which will depend on what you are trying to do.
self.privilegis is not defined anywhere inside Privilegis. I believe you want it to be self.privilegis_type
this means having something like this:
class Privilegis:
def __init__(self, privilegis_type=None): # could be anything
self.privilegis_type = ['Allow to delete users', 'Allow to rename users', 'Allow to ban users']
def show_privilegis(self):
print('Special admins privilegis are: ' + ', '.join(self.privilegis_type)) # fixed that also

Saving from dictionary to file (error)

I'm taking my first Python class so please bear with me, I have ZERO experience in programming but I'm very eager to learn. If you could steer me in the right direction I'd really appreciate it. Thank you in advance.
I've looked through previous questions but I wasn't able to find one that fully helped/explained where I'm getting stuck. I have a dictionary that stores team members(names, phone, jersey) and need to be able to write this to a file. Below is what I currently have, when I run this I get the error AttributeError:'dict' object has no attribute 'getname'.
class Member:
def get name(self):
return self.name
def get phone(self):
return self.phone
def get jersey(self):
return self.jersey
members={}
def saveData(members, filename):
filename=input("Filename to save:")
outFile=open(filename,"wt")
for x in members.keys():
name=members[x].getname
phone=members[x].getphone
jersey=members[x].getjersey
outFile.write(name+","+phone","+jersey+"\n")
print("Data Saved")
outFile.close()
Member class
You've put a space in the function name, so it won't work.
Too, you don't seem to have an __init__ function.
class Member:
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
def get_name(self):
return self.name
def get_phone(self):
return self.phone
def get_jersey(self):
return self.jersey
Anyway, it's a lot easier that just don't make these get functions; the user can get the variables of a class using the dot syntax.
class Member:
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
shell:
>>> member1 = Member("Dave", "123456789", "red")
>>> member.name
'Dave'
>>> member.phone
'123456789'
>>> member.jersey
'red'
saveData function
It won't work, you should do this:
def saveData(members): # don't include filename, it's going to be redefined later
filename = input("Filename to save: ") # space at the end
with open(filename, 'wt') as outFile: # using with for files is recommended
# then you don't need to close the file
for x in members: # you can directly iterate from a dict
name = x.get_name() # you didn't call the function at all
phone = x.get_phone() # members[x] not necessary
jersey = x.get_jersey()
outFile.write(name+", "+phone+", "+jersey+"\n") #missing + sign
print("Data Saved")
Working example
__init__.py
class Member:
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
def get_name(self):
return self.name
def get_phone(self):
return self.phone
def get_jersey(self):
return self.jersey
def saveData(members):
filename = input("Filename to save: ")
with open(filename, 'wt') as outFile:
for x in members:
name = x.get_name()
phone = x.get_phone()
jersey = x.get_jersey()
outFile.write(name+", "+phone+", "+jersey+"\n")
print("Data Saved")
IDLE shell
>>> members = [Member("Dave", "123456789", "red"),
Member("Tom", "133742097", "yellow"),
Member("Elisa", "122333444", "blue"),
Member("John", "987654321", "blue")
]
>>> saveData(members)
Filename to save: output.txt
Data Saved
output.txt
Dave, 123456789, red
Tom, 133742097, yellow
Elisa, 122333444, blue
John, 987654321, blue
You can define getname, getphone in your Member class as follows:
class Member:
def getname(self):
return self.name
def getphone(self):
return self.phone
def getjersey(self):
return self.jersey
Then you can get values from getters in your saveData function :
name=members[x].getname()
phone=members[x].getphone()
jersey=members[x].getjersey()

Python OOP Factory Pattern

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.

Categories

Resources