python class error str object has no attribute (beginner) - python-3.x

Hi I'm supposed to create knows and meet functions of this class but it keeps giving me different errors, so how I'm supposed to actually do it? Mostly I would like to know how to implement the knows function so I can finish the rest myself. Here's the code
class Person(object):
'''
The Person class implements a single person in network of people knowing each other.
'''
def __init__(self, name):
'''
initializes a new person with the given name. The person initially has no friends.
#param name: the name of the person created.
'''
self.name = name
self.friend = None
def get_friend(self):
'''
Returns the immediate friend of this person.
#return: the immediate friend (person-object) of this person.
'''
return self.friend
def set_friend(self, friend):
'''
Sets the immediate friend of this person.
'''
self.friend = friend
def knows(self, other):
'''
Tests if a person is connected to another by a path.
#param other: the person-object in the other end of the path tested.
#return: true if the persons are connected, false otherwise.
'''
if self.name==None:
return False
while self.name.get_friend() != self.name or self.name.get_friend() != None:
self.name=self.name.get_friend()
while other.get_friend(other) != other.get_name() or other.get_friend() != None:
other=other.get_friend()
if self.get_name() == other.get_name():
return True
else:
return False
# please implement me
def meet(self, other):
'''
Tries to add a path connecting to persons.
#param other: the other end of the connection being introduced (person-object).
#return: true if and only if the persons were not previously connected.
'''
# please implement me
if self.knows(other)==True:
return False
else:
while self.name.get_friend() != self.get_name() or self.get_name() != None:
self.name = self.get_friend()
while other.get_friend() != other.get_name() or other.get_friend() != None:
other=other.get_friend()
self.name.set_friend(other.get_name)
return True
def get_name(self):
'''
Returns a string representation of this Person, containing the name of the person.
#return: the name of the person.
'''
return self.name

I ran your code, and it executed without an error. My guess is that other is a string, and in meet() and knows(), you call other.get_friend(), which is obviously undefined for strings.
>>> mystring = ' '
>>> mystring.get_friend()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'get_friend'
>>>
In réponse to your comment
The reason you are getting NoneType is because you are assigning other.get_friend() to other, which assigns other to self.friend, which you set to None in your __init__. Try calling set_friend before you call other=other.get_friend().

Related

How do I return values of one class method to another class method?

I am new to Classes and want to know how to return values from one class method to another. Below is the code and I want to return the queues from arrive() function to next_customer() function.
class DonutQueue():
def __init__(self):
self.queue=[]
self.queue2= []
def arrive(self,name,vip):
self.name = name
self.vip = vip
if self.vip==1:
self.queue2.append(self.name)
return self.queue2
else:
self.queue.append(self.name)
return self.queue
def next_customer(self):
while not self.queue2== []:
if not self.queue2==[]:
return self.queue
else:
return self.queue2
def main():
n = int(input("Enter the number of customers you want to add"))
for i in range(0,n):
name = input("Enter their name")
vip= int(input("Are they a VIP"))
DonutQueue().arrive(name,vip)
print(DonutQueue().next_customer())
If I add the below statement in the next_customer function, I get the mentioned error:
a = self.arrive(self.name,self.vip)
Error:
AttributeError: 'DonutQueue' object has no attribute 'name'
The problem is when I call next_customer() it returns None because I am getting values from init instead of arrives()
in python you have to define members in the __init__ function means. in your case you defined the self.name member only in arrive thats why its not available (and throws an exception) in your case.

Function not Defined in Class

I am having trouble with a coding project in which I am trying to use classes in python to make a card game (cheat). However, when creating the player class, one of the functions that was previously defined within the class is shown as undefined. I cannot figure out the reason, and any suggestion is appreciated. Below is the definition of the classes
class card(object):
def __init__(self,rank,suit):
self.rank = rank
self.suit = suit
class player(object):
def __init__ (self):
self.number = number
self.hand = list()
#Here, hand is a list of the card class that was distributed with a suit and a rank
def check_card(self,player_rank,player_suit):
for card in self.hand:
if card.rank == player_rank and card.suit == player_suit:
return True
break
return False
def play_card(self):
suit = input('what is the suit?')
rank = input('what is the rank?')
if check_card(self,rank,suit):
print(True)
else:
print(False)
Here is the actual code that will run it
player = player()
player.play_card()
The following error was received:
NameError: name 'check_card' is not defined
I have been troubleshooting and looking at different solutions, including moving the functions outside the class, but it continues to display the same error. Can anyone point out the mistake? Thanks!
You have the following two issues in your code
The way you passed self to the check_card function is wrong. You must call it in this way
self.check_card(rank,suit)
The second issue is that the number is not defined. Thus I passed it as an argument while initializing the player. Feel free to make changes for that.
This is the corrected code :
class card(object):
def __init__(self,rank,suit):
self.rank = rank
self.suit = suit
class player(object):
def __init__ (self, number):
self.number = number
self.hand = list()
#Here, hand is a list of the card class that was distributed with a suit and a rank
def check_card(self,player_rank,player_suit):
for card in self.hand:
if card.rank == player_rank and card.suit == player_suit:
return True
break
return False
def play_card(self):
suit = input('what is the suit?')
rank = input('what is the rank?')
if self.check_card(rank,suit):
print(True)
else:
print(False)
player = player(3)
player.play_card()
Output :
what is the suit?spade
what is the rank?3
False
Based on this document the function call in python class is self.xxxx(args) (xxxx is denoted function name)
therefore the correct version of play_card function is shown as following.
enter code here
def play_card(self):
suit = input('what is the suit?')
rank = input('what is the rank?')
if self.check_card(rank,suit):
print(True)
else:
print(False)

AssertionError: <bound method comment.created_at of <solution.comment object at 0x7f3db6beba58>> is not an instance of <class 'datetime.datetime'>

I am new to python and am trying to learn OOP. I have this mock up quiz that i have been trying to solve. So far am able to pass 5 test
Here is the challenge
Users come in 3 flavors, normal users, moderators, and admins. Normal users can only create new comments, and edit the their own comments. Moderators have the added ability to delete comments (to remove trolls), while admins have the ability to edit or delete any comment.
Users can log in and out, and we track when they last logged in
Comments
Encapsulation of Properties
All classes should have no publicly accessible fields
You should make sure you at least "hide" the required fields, for example, using _name instead of _name. Alternatively, feel free to use a better solution as extra credit.
The method-based API is provided. These must be completed as-is.
Additional methods are allowed, though remember to keep read-only properties read-only.
Instantiation
Classes should be instantiated with properties (as provided), to create instances with values already assigned.
User/Moderator/Admin defaults:
Should be marked as not logged in
Should return None for the last logged in at property
Comment defaults:
Should set the current timestamp for the created at property upon instantiation
Replied To is optional, and should be None if not provided.
Inheritance & Access Control
User
Users can be logged in and out.
When logging in, set the last_logged_in_at timestamp. Do not modify this timestamp when logging out
Users can only edit their own comments
Users cannot delete any comments
Moderator is a User
Moderators can only edit their own comments
Moderators can delete any comments
Admin is both a User and a Moderator
Admins can edit any comments
Admins can delete any comments
Composition
Comments contain a reference to the User who created it (author)
Comments optionally contain a reference to another comment (replied_to)
When converting to a string (to_string), the following format is used:
No replied to:
message + " by " + author.name
With replied to:
message + " by " + author.name + " (replied to " + repliedTo.author.name + ")"
this is my solution
import datetime
class user:
def __init__(self, name, lastloggedIn = None):
self.name = name
self.loggedIn = False
self.lastloggedIn = None
def name(self):
return self.name
def name(self, value):
self.name = value
def is_logged_in(self):
return self.loggedIn
def last_logged_in_at(self):
return self.lastloggedIn
def log_in(self):
self.loggedIn = True
self.lastloggedIn = datetime.datetime.utcnow()
def log_out(self):
self.loggedIn = False
def can_edit(self, comment):
if comment.author.name == self.name:
return True
else:
return False
def can_delete(self, comment):
return False
# def to_string(self):
# pass
class moderator(user):
def __init__(self, name):
user.__init__(self, name)
def can_delete(self, comment):
return True
class admin(moderator):
def __init__(self, name):
moderator.__init__(self, name)
def can_edit(self, comment):
return True
class comment:
def __init__(self, author, message, replied_to = None, createdAt = None):
self.createdAt = datetime.datetime.now()
self.author = author
self.message = message
self.replied_to = replied_to
def author(self):
return self._author
def author(self, value):
self.author = value
def message(self):
return self.message
def message(self, value):
self.message = value
def created_at(self):
return self.createdAt
def replied_to(self):
return self.replied_to
def replied_to(self, value):
self.replied_to = value
def to_string(self):
if self.replied_to == None:
return self.replied_to + " by " + self.author.name
import unittest
user1 = user('User 1')
mod = moderator('Moderator')
class Test(unittest.TestCase):
def test_instantiation(self):
self.assertEqual(user1.name,'User 1', 'User name is set correctly')
user1.name = 'User 1 Updated'
self.assertEqual(user1.name,'User 1 Updated', 'User name can be updated')
self.assertIsInstance(mod, user, 'Moderator is a user')
Am getting two main errors. the last_logged_in method should return None and the datetime.datetime.now() doesn't seem to be working correctly
AssertionError: <bound method comment.created_at of <solution.comment object at 0x7fd5a21d0668>> is not an instance of <class 'datetime.datetime'>
AssertionError: <bound method user.last_logged_in_at of <[35 chars]ba8>> != None : Last logged in date is not set by default
Let's start with the first error:
AssertionError: <bound method comment.created_at of <solution.comment object at 0x7fd5a21d0668>> is not an instance of <class 'datetime.datetime'>
ITsays you are passing datetime instance. Let's check:
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2018, 11, 21, 10, 28, 26, 996940) # this is datetime instance
what you can do is convert it to string and pass it:
>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2018-11-21 06:51:22'
Like:
class comment:
def __init__(self, author, message, replied_to = None, createdAt = None):
self.createdAt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
For the second error:
AssertionError: <bound method user.last_logged_in_at of <[35 chars]ba8>> != None : Last logged in date is not set by default
You are not setting lastloggedIn:
def __init__(self, name, lastloggedIn = None):
self.name = name
self.loggedIn = False
self.lastloggedIn = lastloggedIn
and same here you are passing an instance:
>>> datetime.datetime.utcnow()
datetime.datetime(2018, 11, 21, 6, 46, 25, 248409)
change it to return the string instead of an instance:
def log_in(self):
self.loggedIn = True
self.lastloggedIn = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")

Python - How to return a the details of each Room instance in a list, from inside of a Map instance

I am working on a small text adventure in python, and am attempting to use classes. I'm not very well versed in OOP and although I feel like I'm slowly gaining a greater understanding...I know that I still have a ways to go.
This is my room class
#!usr/bin/env python3
"""
A room class and a method to load room data from json files
"""
import json
class Room():
def __init__(
self,
id = "0",
name = "An empty room",
desc = "There is nothing here",
items = {},
exits = {},
):
self.id = id
self.name = name
self.desc = desc
self.items = items
self.exits = exits
def __str__(self):
return "{}\n{}\n{}\n{}".format(self.name, self.desc, self.items, self.exits)
# Create method to verify exits
def _exits(self, dir):
if dir in self.exits:
return self.exits[dir]
else:
return None
def north(self):
return self._exits('n')
def south(self):
return self._exits('s')
def east(self):
return self._exits('e')
def west(self):
return self._exits('w')
# Create method to get room info from json file
def get_room(id):
ret = None
with open("data/{}.json".format(str(id)) , "r") as f:
jsontext = f.read()
d = json.loads(jsontext, strict = False)
d['id'] = id
ret = Room(**d)
return ret
This is my map class
#!/usr/bin/env python3
from rooms import *
"""
Map class used to build a map from all of the rooms
"""
class Map():
def __init__(self, rooms = {}):
self.rooms = rooms
def __str__(self):
return map(str, rooms)
def build_map(id, num_of_rooms):
rooms = {}
room_count = 0
while room_count < num_of_rooms:
rooms[id] = get_room(id)
id += 1
room_count += 1
return rooms
a_map = Map(build_map(1, 3))
def test_map(map):
return map.rooms
print(test_map(a_map))
I'm not understanding why test_map only returns a list of objects, and was wondering how I might be able to receive the actual list of rooms so that I can confirm that they were created properly. I'm sure that I'm just going about this the COMPLETE wrong way...which is why I've come here with the issue.
For general information about __str__ and __repr__, Check out this answer.
In this case, here's what's happening:
Your __str__ function on Map doesn't return a string, it returns a map object. __str__ must return a string.
That's not causing an error because the function isn't getting called, here: test_map returns the given Map's rooms attribute, which is a dictionary. If you tried to do print(a_map) you'd get an exception.
Dictionaries have their own __str__ method, which is getting called here but the dictionary's __str__ method calls __repr__ on its members, which you haven't defined. (See the linked answer for details on why this is so.)
When you haven't defined a __repr__ for your class, you get the __repr__ from object, which is why your print(test_map(a_map)) gives you output like {1: <__main__.Room instance at 0x7fca06a5b6c8>, 2: <__main__.Room instance at 0x7fca06ac3098>, 3: <__main__.Room instance at 0x7fca06ac36c8>}.
What I'd suggest:
Write __repr__ functions for both Map and Room.
Have Map.__repr__ return a string that indirectly relies on Room.__repr__, something like the following:
def __repr__(self):
return '<Map: {}>'.format(self.rooms)
This isn't maybe the best long-term approach - what if you have a map with a hundred rooms? - but it should get you going and you can experiment with what works best for you.

How to spot my error in Python?

Write a class named Person with data attributes for a person’s name, address, and telephone number. Next, write a class named Customer that is a subclass of the Person class.
The Customer class should have a data attribute for a customer number and a Boolean data attribute indicating whether the customer wishes to be on a mailing list. Demonstrate an instance of the Customer class in a simple program.'
This is what I have for my code, but I keep getting the following error:
Traceback (most recent call last):
File "/Users/ryanraben/Desktop/person1.py", line 45, in <module>
import customer
ModuleNotFoundError: No module named 'customer'
I have been struggling with this class this semester. I found someone asking a similar question here in Stack Overflow but their code was very different than what I had (and if I copied their code I still could not get the correct results). This was a video module and I entered my code as it appeared on the instructor's screen, but obviously I didn't do it right because his code works and mine does not.
class Person:
def __init__(self, name, address, phone):
self.__name = name
self.__address = address
self.__phone = phone
def set_name (self, name):
self.__name = name
def set_address (self, address):
self.__address = address
def set_phone (self, phone):
self.__phone = phone
def get_name (self):
return self.__name
def get_address (self):
return self.__address
def get_phone (self):
return self.__phone
class Customer (Person):
def __init__(self, name, address, phone, customer_number, mailing_list):
Person.__init__(self, name, adress, phone)
self.__customer_number = customer_number
self.__mailing_list = mailing_list
def set_customer_number (self, customer_number):
self.__customer_number = customer_number
def set_mailing_list(self, mailing_list):
self.__mailing_list = mailing_list
def get_customer_number(self):
return self.__customer_number
def get_mailing_list (self):
return self.__mailing_list
import customer
name = input ('Name: ')
address = input ('Address: ')
phone = input ('Phone: ')
customer_number = input ('Customer number: ')
mail = input ('Include in mailing list? (y/n): ')
if mail.lower()=='y':
mailing_list = True
else:
mailing_list = False
my_customer = customer.Customer (name, address, phone, customer_number, mailing_list)
print ('Customer Information')
print ('-----------------------------')
print ('Name: ', my_customer.get_name())
print ('Address: ', my_customer.get_address())
print ('Phone: ', my_customer.get_phone())
print ('Customer number: ', my_customer.get_customer_number())
print ('Mailing list: ', my_customer.get_mailing_list())
This is a pretty common error:
You're attempting to import the library of customer and your IDE is simply not able to find this file.
Since you're defining the Class Customer I can't see any reason why you would need to import this non-existant library.
Consequently, I suggest you delete the line import customer.
That is unless I've misunderstood something.
remove this line(import customer) and remove customer from 'customer.Customer' while creating the object. After all of this you have error of 'adress' not defined. Find this attribute in your code and change it to address. Thats All dear.

Resources