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.
Related
I am working on an optapy project and I am getting this error in the solver phase.
\optapy\optaplanner_api_wrappers.py", line 310, in solver_factory_create
return SolverFactory.create(solver_config)
TypeError: Unable to convert
You can find here my domain.py file and the main.py file
domain.py
#I defined the problem facts here
#planning_solution
class ReservationTable:
def __init__(self, timeslot_list, seat_list, reservation_list, employee_list, score = None):
self.timeslot_list = timeslot_list
self.seat_list = seat_list
self.reservation_list = reservation_list
self.employee_list = employee_list
self.score = score
#problem_fact_collection_property(Timeslot)
#value_range_provider('timeslotRange')
def get_timeslot_list(self):
return self.timeslot_list
#problem_fact_collection_property(Seat)
#value_range_provider('seatRange')
def get_seat_range(self):
return self.seat_list
#problem_fact_collection_property(Employee)
#value_range_provider('employeeRange')
def get_seat_list(self):
return self.employee_list
#planning_entity_collection_property(Reservation)
def get_reservation_list(self):
return self.reservation_list
#planning_score(HardSoftScore)
def get_score(self):
return self.score
def set_score(self, newScore):
self.score = newScore
def generate_problem():
#I created here an example of data
return ReservationTable(timeslot_list, seat_list, reservation_list, employee_list)
main.py
solver_config = optapy.config.solver.SolverConfig() \
.withEntityClasses(Reservation) \
.withSolutionClass(ReservationTable) \
.withConstraintProviderClass(define_constraints) \
.withTerminationSpentLimit(Duration.ofSeconds(30))
solver_factory = solver_factory_create(solver_config)
solver = solver_factory.buildSolver()
solution = solver.solve(generate_problem())
print(solution)
Does anyone have an idea about this problem ? Thank you
The issue is in your #constraint_provider (which is not shown in the question). The error was raised when trying to convert the list returned by defined_constraints into a list of Constraint. In particular, the #constraint_provider must return a list of Constraint generated by the constraint_factory parameter. For instance:
from optapy import constraint_provider
from optapy.score import HardSoftScore
from optapy.constraint import Joiners
from domain import Employee, Reservation
#constraint_provider
def define_constraints(constraint_factory):
return [
constraint_factory.for_each(Employee)
.if_not_exists(Reservation, Joiners.equal(lambda employee: employee.name, lambda reservation: reservation.employee.name))
.penalize('Employee not assigned', HardSoftScore.ONE_HARD)
]
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)
The issue: AttributeError: 'str' object has no attribute '_sa_instance_state' and I am uncertain how to fix it.
I believe it is related to the retrieve methods below. Someone on Stacks had a similar issue and it was a simple matter of changing the function...this has not the case for me.
Traceback:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/Users/ack/code/venv/NotssDB/notssdb/test/test.py", line 132, in test1
api.retrieve_assessment_result('baseball', 'Becoming a Leader')
File "/Users/ack/code/venv/NotssDB/notssdb/api/object.py", line 324, in retrieve_assessment_result
filter(Assessment_Result.owner == owner).one()
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/sql/operators.py", line 301, in __eq__
return self.operate(eq, other)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 175, in operate
return op(self.comparator, *other, **kwargs)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 1011, in __eq__
other, adapt_source=self.adapter))
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 1338, in _optimized_compare
state = attributes.instance_state(state)
AttributeError: 'str' object has no attribute '_sa_instance_state'
object.py
def retrieve_assessment_result(self, *args):
id, owner, assessment = None, None, None
if len(args) == 1:
id, = args[0]
elif len(args) == 2:
owner, assessment = args
else:
raise ValueError('Value being passed is an object')
if id is not None:
return self.session.query(Assessment_Result).\
filter(Assessment_Result.id == id).one()
elif owner is not None:
print 'test1', owner
return self.session.query(Assessment_Result).\
filter(Assessment_Result.owner == owner).one()
elif assessment is not None:
print 'test2', assessment
return self.session.query(Assessment_Result).\
filter(Assessment_Result.assessment == assessment).one()
def create_category_rating(self, category_rating_int, category, assessment_result):
new_catrating = Category_Rating(category_rating_int, category, assessment_result)
self.session.add(new_catrating)
print(new_catrating)
self.session.commit()
return(new_catrating)
convenience.py
(inherits from object.py)
def create_category_rating(self, category_rating_int, category_name, username, name):
category = self.retrieve_category(category_name)
owner = self.retrieve_user(username)
assessment = self.retrieve_assessment(name)
assessment_result = self.retrieve_assessment_result(owner, assessment)
return super(ConvenienceAPI, self).create_category_rating(category_rating_int, category, assessment_result)
model.py
class Category_Rating(Base):
__tablename__ = 'category_ratings'
id = Column(Integer, primary_key=True)
category_rating_int = Column(Integer)
category_id = Column(Integer, ForeignKey('categories.category_id'))
category = relationship('Category', backref='category_ratings')
assessment_result_id = Column(Integer, ForeignKey('assessment_results.id'))
assessment_result = relationship('Assessment_Result', backref='category_ratings')
def __init__(self, category_rating_int, category, assessment_result): #OBJECT
self.category_rating_int = category_rating_int
self.category = category
self.assessment_result = assessment_result
def __repr__(self):
return "<Category_Rating(category_rating_int='%s')>" % (self.category_rating_int)
test.py
api = ConvenienceAPI()
api.create_category_rating(2, 'Decision-Making', 'baseball', 'Becoming a Leader')
You problem is exactly as the one in the linked question:
You are assigning a list to a relationship where uselist=False. You should set the single model instance, rather than a list containing it.
In your case property assessment_results is defined as many-to-one relationship (e.g. single Category_Rating can have single Assessment_Results instance, but single Assessment_Results can have multiple Category_Rating instances). If you do following renames previous statements will make much more sense for you:
assessment_results -> assessment_result
assessment_results_id -> assessment_result_id
Assessment_Results -> Assessment_Result
The problem is that assessment_results property expects single instance of Assessment_Results model, but you set it to result of the method retrieve_assessment_results(), which returns list of Assessment_Results. That's why it fails.
UPD
The second problem is in this string filter(Assessment_Result.owner == owner).one(). You try to compare Owner instance with string. You probably want to replace it with something like filter(Owner.name == owner).one(). Can't tell you exactly without seeing these models definitions.
Working with Yaroslav Admin, I did something similar to his suggestion... I added a retrieve method for assessment_result(..) in the convenience.py (api) that would check for strings:
working code:
(this inherits from the object.py file -- shown above)
def retrieve_assessment_result(self, username, name):
owner = self.retrieve_user(username)
assessment = self.retrieve_assessment(name)
return super(ConvenienceAPI, self).retrieve_assessment_result(owner, assessment)
This question already has answers here:
What is the meaning of single and double underscore before an object name?
(18 answers)
Closed 8 years ago.
This is the Traceback I am getting :
Traceback (most recent call last):
File "D:\School\Programming ll\Week 4\2.py", line 42, in
main()
File "D:\School\Programming ll\Week 4\2.py", line 38, in main
print('Name: ',emp.name())
AttributeError: 'ProductionWorker' object has no attribute 'name'
Code:
class Employee(object):
def __init__(self,name,id_number):
self.__name = name
self.__id_number = id_number
def set_name(self, name):
self. __name = name
def set_id_number(self,id_number):
return self.__name
def get_id_number(self):
return self.__id_number
class ProductionWorker(Employee):
def __init__(self, name,id_number,shift_num,pay_rate):
Employee.__init__(self, name, id_number)
self.__shift_num = shift_num
self.__pay_rate = pay_rate
def set_shift_num(self, shift_num):
self.__shift_num= shift_num
def set_pay_rate(self, pay_rate):
self.__pay_rate = pay_rate
#accessor functions for shift_number and pay_rate
def get_shift_num(self):
return self.__shift_num
def get_pay_rate(self):
return self.__pay_rate
def main():
#get the values of employee name, number , shif_number and pay_rate from user.
print ('Enter the following information for the employee')
name=input('Name: ')
id_number=input('Employee number: ')
shift_num=input('Shift number: ')
pay_rate=input ('Pay rate: ')
emp = ProductionWorker(name,id_number,shift_num,pay_rate)
print('Details of employee are shown below: ')
print('Name: ',emp.name())
print('Employee Number: ',emp.get_id_number())
print('Shift Number: ',emp.get_shift_num())
print('Pay Rate: ',emp.get_pay_rate())
main()
Please help me , I have been banging my head for hours now. Thanks
ProductionWorker is not a member of Employee. try instead :
emp = ProductionWorker(name,id_number,shift_num,pay_rate)
You may add a method in the Employee class :
def name(self):
return self.__name
The best way would be to use properties : https://docs.python.org/2/library/functions.html#property
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( )