Trouble Creating Instance of Class - python

I have the code below, but I am getting an error when I try to create an instance of the class.
class Flight():
def __init__(self, capacity):
self.capacity = capacity
self.passengers = []
def add_passenger(self, name):
if not self.open_seats():
return False
self.passengers.append(name)
return True
def open_seats(self):
return self.capacity - len(self.passengers)
f = Flight(3)
people = ["Aicel", "Angela", "Randy", "Monina"]
for person in people:
success = flight.add_passengers(person)
if success:
print(f"Added {person} to flight successfully")
else:
print(f"No available seats for {person}")
This the error message:
Traceback (most recent call last):
File classflight.py Line 19, in <module>
success = flight.add_passenger(person)
NameError: name 'flight' is not defined

The error message tells you: name 'flight' is not defined.
If you look closer at the line in question from the error message (success = flight.add_passenger(person)) and the rest of your code, you see that the Flight instance that you created is not named flight but f. So to make your code work,
either change f = Flight(3) to flight = Flight(3)
or change success = flight.add_passenger(person) to success = f.add_passenger(person)

Related

Modifying an Attribute's value through method

class UniversityAthletics():
def __init__(self, university_name, sport):
self.name = university_name
self.sport = sport
self.tickets_sold = 10
def tickets_sold(self):
"""This just tells you how many tickets have been sold"""
print(str(self.tickets_sold) + " tickets have been sold")
def describe_athletics(self):
print(self.name.title() + " " + self.sport.title())
def in_season(self):
print(self.sport.title() + " is in season.")
def set_tickets_sold(self, numticket):
"""This sets the number of tickets that have been sold"""
self.tickets_sold = numticket
def increment_tickets_sold(self, moretickets):
"""This increments the number of tickets sold"""
self.tickets_sold += moretickets
athletics = UniversityAthletics('salisbury university', 'soccer')
athletics.set_tickets_sold(20)
athletics.tickets_sold()
athletics.increment_tickets_sold(500)
athletics.tickets_sold()
I tried to make an attribute that sets the number of tickets sold 'set_tickets_sold' and then an attribute that changes the number of the tickets 'increment_tickets_sold' but when I try to set the number of tickets and then call the method 'tickets_sold()' i keep receiving an error.
Traceback (most recent call last): File
"E:/WorWic/IntroToProgramming/chapter9/University Athletics part
2.py", line 29, in
athletics.tickets_sold() TypeError: 'int' object is not callable
What did I do wrong?
Your issue is that tickets_sold is both an attribute and a function name. It's getting the attribute and calling that, rather than the function. I suggest renaming your function to something else.

Python AttributeError 'str' object has no attribute '_sID'

I get an error in python ecplise and i didn't found the solution to solve it..
Class:
class Student:
'''
This class is used to store data about the students
It contains:
sID - id of student
sName - name of student
'''
def __init__(self, sID, sName):
'''
Initialized the student
'''
self._sID = sID
self._sName = sName
def getID(self):
'''
Return student id
'''
return self._sID
def setID(self, ID):
self._sID = ID
def setName(self, name):
self._sName = name
def getName(self):
'''
Return student name
'''
return self._sName
def __str__(self):
'''
Converts the student into printable text
'''
msg ='ID: ' + str(self._sID) + ', Name: ' + self._sName
return msg
def __eq__(self, s):
'''
Checks if two students have the same ID and name
'''
return self._sID == s._sID and self._sName == s._sName
Below is the erorr with attribute:
Traceback (most recent call last):
File "C:\Users\crist\workspace\lab5_7\appStart.py", line 16, in <module>
ui.mainMenu()
File "C:\Users\crist\workspace\lab5_7\UI\ui.py", line 80, in mainMenu
self._searchElementMenu(cmd[1])
File "C:\Users\crist\workspace\lab5_7\UI\ui.py", line 57, in _searchElementMenu
self._controller.searchElement(cType, cSearch)
File "C:\Users\crist\workspace\lab5_7\controller\controller.py", line 27, in searchElement
if isinstance(lst[i], Student) == True and lst[i] == eSearch:
File "C:\Users\crist\workspace\lab5_7\domain\student.py", line 55, in __eq__
return self._sID == s._sID and self._sName == s._sName
AttributeError: 'str' object has no attribute '_sID'
Can someone help me?
I can give u more code if is necessary.
The sID is the unique id for every student, and i need this function to verify if more students have the same id.
Thank you so much !
You are trying to use the = operator, with an Student instance and a string.
The error tells that a string instance does not have a _sID variable like:
"test"._sID
I had the same problem - getting the same error message when setting environment in PythonWin. I haven't changed anything, but restarted PythonWin and it was working again as usual.

Create a class within a class and instance in outer scope?

I am trying to implement consumer - producer problem in Python… The one question I have is whether I can create a class within a class and create an object of it in the outer scope as in the code below:
class Main(threading.Thread):
def __init__(self):
processNumber = 0
queue_size=5
self.mutexProducer=thread.allocate_lock()#mutex variablaes
self.mutexConsumer=thread.allocate_lock()
self.mutexTeller=thread.allocate_lock()
self.queue=Queue.Queue(maxsize=queue_size)
self.producer=Producer(processNumber,random.random())
class Producer(threading.Thread):
def __int__(self,ProducerID,serviceTime):
self.id=ProcucerID
self.serviceTime=serviceTime
def run(self):
#mutexProducer.acquire()
#Entering Critical section
print queue.qsize()
if queue.full():
sleep(random.random())
else:
print "Customer %d Enters the Queue" %(self.id)
app=Main()
I am getting the following error:
Traceback (most recent call last): File "/Users/sohil/Desktop/sync.py", line 55, in <module>
app=Main() File "/Users/sohil/Desktop/sync.py", line 36, in __init__
self.producer=Producer(processNumber,random.random()) NameError: global name 'Producer' is not defined
Change the order.
class Producer(threading.Thread):
def __int__(self,ProducerID,serviceTime):
self.id=ProcucerID
self.serviceTime=serviceTime
def run(self):
#mutexProducer.acquire()
#Entering Critical section
print queue.qsize()
if queue.full():
sleep(random.random())
else:
print "Customer %d Enters the Queue" %(self.id)
class Main(threading.Thread):
def __init__(self):
processNumber = 0
queue_size=5
self.mutexProducer=thread.allocate_lock()#mutex variablaes
self.mutexConsumer=thread.allocate_lock()
self.mutexTeller=thread.allocate_lock()
self.queue=Queue.Queue(maxsize=queue_size)
self.producer=Producer(processNumber,random.random())
Python is an interpreted language which executes from top to bottom so any dependencies must be declared at the top.

Python :TypeError: this constructor takes no arguments

When the user enters an email address, and the program reads the email and display it according to its criteria (e.g yeo.myy#edu.co), like criteria:
username is yeo.myy
domain is edu.co
I know its something to do with the "#".
this is the code
class Email:
def __int__(self,emailAddr):
self.emailAddr = emailAddr
def domain(self):
index = 0
for i in range(len(emailAddr)):
if emailAddr[i] == "#":
index = i
return self.emailAddr[index+1:]
def username(self):
index = 0
for i in range(len(emailAddr)):
if emailAddr[i] == "#" :
index = i
return self.emailAddr[:index]
def main():
emailAddr = raw_input("Enter your email>>")
user = Email(emailAddr)
print "Username = ", user.username()
print "Domain = ", user.domain()
main()
this is the error I got:
Traceback (most recent call last):
File "C:/Users/Owner/Desktop/sdsd", line 29, in <module>
main()
File "C:/Users/Owner/Desktop/sdsd", line 24, in main
user = Email(emailAddr)
TypeError: this constructor takes no arguments
def __int__(self,emailAddr):
Did you mean __init__?
def __init__(self,emailAddr):
You're also missing a couple selfs in your methods, and your returns are improperly indented.
def domain(self):
index = 0
for i in range(len(self.emailAddr)):
if self.emailAddr[i] == "#":
index = i
return self.emailAddr[index+1:]
def username(self):
index = 0
for i in range(len(self.emailAddr)):
if self.emailAddr[i] == "#" :
index = i
return self.emailAddr[:index]
Result:
Username = yeo.myy
Domain = edu.co
Incidentally, I recommend partition and rpartition for splitting a string into two pieces on a given separator. Sure beats keeping track of indices manually.
def domain(self):
return self.emailAddr.rpartition("#")[2]
def username(self):
return self.emailAddr.rpartition("#")[0]
This error may happen if you type def _init_ with a single underline instead of def __init__ with double underlines before and after init.
class Employee:
def __init__(self,Name,Age,Salary,Gender):
self.Name = Name
self.Age = Age
self.Salary= Salary
self.Gender = Gender
def show_employee_deatils(self):
print("Name of the employee is ",self.Name)
print("Age of the employee is ",self.age)
print("Salary of the employee is ",self.salary)
print("gender of the employee is ",self.gender)
e1 = Employee('Shubham',25,25000,'male')
e1. show_Employee_deatils( )

Class Attribute is clearly there, but python cant find it

Why am i getting this attribute error?
class GameState(object):
"""Keeps track game state variables"""
def __init__(self, convo_flag=0, characters_talked_to=0, convo_log=(None)):
self.convo_flag = convo_flag
self.characters_talked_to = characters_talked_to
self.convo_log = convo_log
def welcome_screen():
global LAST_NAME
global BULLY
global DAY
raw_input(messages.WELCOME)
LAST_NAME = raw_input(messages.LAST_NAME)
BULLY = characters.random_character(cclass='Camper', gender='m')
print 'Your name is Pickett %s' % LAST_NAME
messages.print_messages([
messages.EXPLANATION,
messages.BUS_LOADING,
messages.CRACK,
messages.GAME_KID_LOST])
return week_one(DAY)
def week_one(day):
if day == 1:
messages.print_messages(messages.WEEK_ONE[day])
campers = characters.random_character_sample(cclass='Camper', count=5)
people_outside_theater = campers + [characters.TROID]
while GameState.characters_talked_to != 3:
I dont get why im getting this attribute error, i totally declared it in that constructor, is there something i am missing were i need to declare it outside the constructor? This is really racking my brain.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pickett.py", line 44, in welcome_screen
return week_one(DAY)
File "pickett.py", line 52, in week_one
while GameState.characters_talked_to != 3:
AttributeError: type object 'GameState' has no attribute 'characters_talked_to'
You need to create an instance in order you use your class like this:
gameState = GameState()
while gameState.characters_talked_to != 3:
In your code you were trying to access class-level attribute which is not defined in your class.
Your __init__ function sets characters_talked_to on self, which is an instance of GameState.
You did not set it on GameState, which is a class.
Neither did you create any instances of GameState, so in any case __init__ is never called by your program.

Categories