Is there a way to append from user input in a class? - python

Is there a way I could implement user input to create a new entry in this class I defined?
class Pulsar:
'Collective base of all Pulsars'
pulsarCount = 0
def __init__(self, name, distance):
self.name = name
self.distance = distance
Pulsar.pulsarCount += 1
def displayCount(self):
print( "Total Pulsars %d" % Pulsar.pulsarCount)
def displayPulsar(self):
print( "Name : ", self.name, ", Distance: ", self.distance)
"This creates the first object"
pulsar1 = Pulsar("B1944+17", "979 Lightyears")
"This creates the second pulsar in the class"
pulsar2 = Pulsar("J2129-5721", "1305 Lightyears")
pulsar1.displayPulsar()
pulsar2.displayPulsar()
print( "Total Pulsars %d" % Pulsar.pulsarCount)
I'm hoping for the user to be able to input their own name/distance and have it append to my current defined variables.

Depending on what you're doing with the Pulsar objects, a class may be overkill.
class Pulsar:
def __repr__(self) -> str:
return f'Pulsar({self.name!r}, {self.distance!r})'
def __init__(self, distance: str, name: str) -> None:
self.name: str = name
self.distance: str = distance
num_pulsars_input = int(input('How many pulsars do you wish to create: '))
pulsar_list = []
for _ in range(num_pulsars_input):
curr_p_name = input('Enter pulsar name: ')
curr_p_dist = input('Enter pulsar distance: ')
curr_p = Pulsar(curr_p_name, curr_p_dist)
pulsar_list.append(curr_p)
print(pulsar_list)

class Pulsar:
'Collective base of all Pulsars'
pulsarCount = 0
def __init__(self, name, distance):
self.name = name
self.distance = distance
Pulsar.pulsarCount += 1
def displayCount(self):
print( "Total Pulsars %d" % Pulsar.pulsarCount)
def displayPulsar(self):
print( "Name : ", self.name, ", Distance: ", self.distance)
"This creates the first object"
pulsar1 = Pulsar("B1944+17", "979 Lightyears")
"This creates the second pulsar in the class"
pulsar2 = Pulsar("J2129-5721", "1305 Lightyears")
pulsar1.displayPulsar()
pulsar2.displayPulsar()
print( "Total Pulsars %d" % Pulsar.pulsarCount)
# New code
users_name = input('Your name: ')
distance = input('The distance: ')
pulsar1.name = users_name
pulsar1.distance = distance
# Then you can wrap this in a function if you want

Related

java.lang.IllegalStateException: 2 members with a #ValueRangeProvider annotation must not have the same id (timeslotRangeLS)

Trying to generate school timetable with lab hours.
Kindly help me to solve this error! Thanks in advance.
Here is my code!
#planning_solution
class TimeTable:
timeslot_list: list[Timeslot]
timeslot_list1: list[Timeslot]
room_list: list[Room]
lesson_list: list[Lesson]
lab_list: list[Lab]
score: HardSoftScore
def __init__(self, timeslot_list, timeslot_list1, room_list, lesson_list,lab_list,
score=None):
self.timeslot_list = timeslot_list
self.timeslot_list1 = timeslot_list1
self.room_list = room_list
self.lesson_list = lesson_list
self.lab_list = lab_list
self.score = score
#problem_fact_collection_property(Timeslot)
#value_range_provider("timeslotRangeLS")
def get_timeslot_list(self):
return self.timeslot_list
#problem_fact_collection_property(Timeslot)
#value_range_provider("timeslotRangeLB")
def get_timeslot_list1(self):
return self.timeslot_list1
#problem_fact_collection_property(Room)
#value_range_provider("roomRange")
def get_room_list(self):
return self.room_list
#planning_entity_collection_property(Lesson)
def get_lesson_list(self):
return self.lesson_list
#planning_entity_collection_property(Lab)
def get_lab_list(self):
return self.Lab_list
#planning_score(HardSoftScore)
def get_score(self):
return self.score
def set_score(self, score):
self.score = score
def __str__(self):
return (
f"TimeTable("
f"timeslot_list={format_list(self.timeslot_list)},\n"
f"timeslot_list1={format_list(self.timeslot_list1)},\n"
f"room_list={format_list(self.room_list)},\n"
f"lesson_list={format_list(self.lesson_list)},\n"
f"lab_list={format_list(self.lab_list)},\n"
f"score={str(self.score.toString()) if self.score is not None else 'None'}"
f")"
)
Trying to get the 2 timeslots one for lesson(1 hour) and one for lab(2 hour).Here is my #planning_solution.
I defined 2 #planning_entity for both lab & lesson with #value_range_provider.
#planning_entity
class Lab(Base):
id: int
subject: str
teacher: str
student_group: str
timeslot1: Timeslot
room: Room
def __init__(self, id, subject, teacher, student_group, timeslot1 = None, room=None):
self.id = id
self.subject = subject
self.teacher = teacher
self.student_group = student_group
self.timeslot1 = timeslot1
self.room = room
#planning_variable(Base, value_range_provider_refs=['roomRange', 'timeslotRangeLB'],
graph_type=PlanningVariableGraphType.CHAINED)
#planning_id
def get_id(self):
return self.id
#planning_variable(Timeslot, ["timeslotRangeLB"])
def get_timeslot1(self):
return self.timeslot1
#value_range_provider(range_id = "timeslotRangeLB", value_range_type = Timeslot)
def get_possible_timeslot_list1(self):
return self.subject.teacher.student_group.room_list
def set_timeslot1(self, new_timeslot):
self.timeslot1 = new_timeslot
#planning_variable(Room, ["roomRange"])
def get_room(self):
return self.room
def set_room(self, new_room):
self.room = new_room
def __str__(self):
return (
f"Lab("
f"id={self.id}, "
f"timeslot1={self.timeslot1}, "
f"room={self.room}, "
f"teacher={self.teacher}, "
f"subject={self.subject}, "
f"student_group={self.student_group}"
f")"
)
#planning_entity
class Lesson(Base):
id: int
subject: str
teacher: str
student_group: str
timeslot: Timeslot
room: Room
def __init__(self, id, subject, teacher, student_group, timeslot=None, room=None):
self.id = id
self.subject = subject
self.teacher = teacher
self.student_group = student_group
self.timeslot = timeslot
self.room = room
#planning_variable(Base, value_range_provider_refs=['timeslotRangeLS', 'roomRange'],
graph_type=PlanningVariableGraphType.CHAINED)
#planning_id
def get_id(self):
return self.id
#planning_variable(Timeslot, ["timeslotRangeLS"])
def get_timeslot(self):
return self.timeslot
#value_range_provider(range_id = "timeslotRangeLS", value_range_type = Timeslot)
def get_possible_timeslot_list(self):
return self.subject.teacher.student_group.room_list
# return self.course.teacher.department.room_list
def set_timeslot(self, new_timeslot):
self.timeslot = new_timeslot
#planning_variable(Room, ["roomRange"])
def get_room(self):
return self.room
def set_room(self, new_room):
self.room = new_room
def __str__(self):
return (
f"Lesson("
f"id={self.id}, "
f"timeslot={self.timeslot}, "
f"room={self.room}, "
f"teacher={self.teacher}, "
f"subject={self.subject}, "
f"student_group={self.student_group}"
f")"
)
The issue is you defined #value_range_provider(range_id = "timeslotRangeLS") on both your #planning_solution and your #planning_entity. You can only have one; if you want the value range to apply to every entity, do it on the #planning_solution. If you want each planning entity to have it own value range that only applies to it, do it on the #planning_entity. If you want to combine a value range that contains common values for all entities, and a value range that is per entity, use a #value_range_provider on the #planning_solution, and a #value_range_provider on the entity, but give them different ids (ex: #value_range_provider(range_id = "timeslotRangeLSSolution") and #value_range_provider(range_id = "timeslotRangeLSEntity"), and in the #planning_variable, use both range ids in the list (ex: #planning_variable(Room, ["timeslotRangeLSSolution", "timeslotRangeLSEntity"])

How can I print each item in an unknown length list that is a class attribute as a string in python?

I have a class (Student) with different attributes, such as studentId, address, and courses. My str method for the class returns all the information that the user put in. However, for the attributes that are lists, such as courses, the location of the information is printed out instead of the actual information. Here is the code (sorry it's a little long, there's a bunch of classes):
class Person:
__name = None
__age = None
__address = None
def __init__(self, name, age=0, address=None):
self.set_name(name)
self.set_age(age)
self.set_address(address)
def __str__(self):
return 'Name: ' + self.__name + '\n' + \
'Age: ' + str(self.__age) + '\n' + \
'Address: ' + str(self.__address)
def set_name(self, name):
self.__name = name
def get_name(self):
return self.__name
def set_age(self, age):
self.__age = age
def get_age(self):
return self.__age
def set_address(self, address):
self.__address = address
def get_address(self):
return self.__address
class Student(Person):
def __init__(self, name, studentID= None, age= 0, address= None):
super(Student, self).__init__(name, age, address)
self.set_studentID(studentID)
self.__courses =[]
def __str__(self):
result = Person.__str__(self)
result += '\nStudent ID:' + self.get_studentID()
for item in self.__courses:
result += '\n ' + str(item)
return result
def set_studentID(self, studentID):
if isinstance(studentID, str) and len(studentID.strip()) > 0:
self.__studentID = studentID.strip()
else:
self.__studentID = 'NA'
def get_studentID(self):
return self.__studentID
def add_course(self, course):
print('in add_course')
self.__courses.append(course)
def get_courses(self):
for i in range(len(self.__courses)):
return self.__courses[i]
class Course:
__courseName = None
__dept = None
__credits = None
def __init__(self, courseName, dept= 'GE', credits= None):
self.set_courseName(courseName)
self.set_dept(dept)
self.set_credits(credits)
def __str__(self):
return self.get_courseName() + '/' + self.get_dept() + '/' + str(self.get_credits())
def set_courseName(self, courseName):
if isinstance(courseName, str) and len(courseName.strip()) > 0:
self.__courseName = courseName.strip()
else:
print('ERROR: Name must be a non-empty string')
raise TypeError('Name must be a non-empty string')
def get_courseName(self):
return self.__courseName
def set_dept(self, dept):
if isinstance(dept, str) and len(dept.strip()) > 0:
self.__dept = dept.strip()
else:
self.__dept = "GE"
def get_dept(self):
return self.__dept
def set_credits(self, credits):
if isinstance(credits, int) and credits > 0:
self.__credits = credits
else:
self.__credits = 3
def get_credits(self):
return self.__credits
students = []
def recordStudentEntry():
name = input('What is your name? ')
age = input('How old are you? ')
studentID= input('What is your student ID? ')
address = input('What is your address? ')
s1 = Student(name, studentID, int(age), address)
students.append(s1)
s1.add_course(recordCourseEntry())
print('\ndisplaying students...')
displayStudents()
print()
def recordCourseEntry():
courses = []
for i in range(2):
courseName = input('What is the name of one course you are taking? ')
dept = input('What department is your course in? ')
credits = input('How many credits is this course? ')
c1 = Course(courseName, dept, credits)
print(c1)
courses.append(c1)
displayCourses(courses)
return courses
def displayCourses(courses):
print('\ndisplaying courses of student... ')
for c in range(len(courses)):
print(courses[c])
def displayStudents():
for s in range(len(students)):
print()
print(students[s])
recordStudentEntry()
This is how the code above prints out the 'displaying students...' part:
displaying students...
Name: sam
Age: 33
Address: 123 st
Student ID:123abc
[<__main__.Course object at 0x000002BE36E0F7F0>, <__main__.Course object at
0x000002BE36E0F040>]
I know that it is printing out the location because I need to index into the list. However, the length of the list will be different every time. Normally if I wanted to index into a list, for example, to print a list of names, I would do:
listOfNames = ['sam', 'john', 'sara']
for i in range(len(listOfNames)):
print(listOfNames[i])
or
listOfNames = ['sam', 'john', 'sara']
for i in listOfNames:
print(i)
(not sure what if any difference there is between the 2 ways since they both print out the same way:)
sam
john
sara
How can I write something like the indexing into a list technique shown here in my str method for my class so that it prints the information and not the location?
It would be good to keep to the standard conventions for Python, such as naming
private attributes for objects with single underscores, not double underscores.
The latter are reserved for Python "internal" attributes and methods.
Also, it is convention to use object attributes for objects with get/set methods,
not class attributes. This will make it easier to inspect your objects, while
still maintaining data hiding. Example:
class Course:
def __init__(self, courseName, dept= 'GE', credits= None):
self._courseName = None
self._dept = None
self._credits = None
self.set_courseName(courseName)
...
Your question about why the courses don't print out the way you expected
is rooted in a programming error with the way you programmed the recording
of courses. In recordCourseEntry(), you record two courses and put them
in a list. However, you pass that to your Student object using a method
intended for one course at a time. My suggested fix would be:
...
# s1.add_course(recordCourseEntry())
courses = recordCourseEntry()
for course in courses:
s1.add_course(course)
...
This will probably be enough to get you going. An example output I got was:
Name: Virtual Scooter
Age: 33
Address: 101 University St.
Student ID:2021
ff/GE/3
gg/GE/3

Driver Class Not Returning Values - Python

My Python Class is not returning any values from using a driver to test. Is there anything wrong? All of the files are in the same folder and other similar classes are able to run and produce values.
Class:
class Person:
#Initializer
def __init__(self, first_name='', last_name='', phone_number='', address=None, social_sec_num='', emailAddress=''):
self.setFirstName(first_name)
self.setLastName(last_name)
self.setPhoneNumber(phone_number)
self.setAddress(address)
self.setSocialSecNum(social_sec_num)
self.setEmailAddress(emailAddress)
#Mutator
def setFirstName(self, first_name):
self.__first_name = first_name
def setLastName(self, last_name):
self.__last_name = last_name
def setPhoneNumber(self, phone_number):
self.__phone_number = phone_number
def setAddress(self, address):
self.__address = address
def setSocialSecNum(self, social_sec_number):
self.__social_sec_num = social_sec_num
def setEmailAddress(self, emailAddress):
self.__emailAddress = emailAddress
#Accessor Methods
def getFirstName(self):
return self.__first_name
def getLastName(self):
return self.__last_name
def getPhoneNumber(self):
return self.__phone_number
def getAddress(self):
return self.__address
def getSocialSecNum(self):
return self.__social_sec_num
def getEmailAddress(self):
return self.__emailAddress
#String Representation
def __str__(self):
people_string = \
"First Name: %s" %self.getFirstName() + "\n" +\
"Last Name: %s" %self.getLastName() + "\n" +\
"Phone Number: %s" %self.getPhoneNumber() + "\n" +\
"Address: %s" %self.getAddress() + "\n" +\
"Social Security Number: %s" %self.getSocialSecNum() + "\n" +\
"Email Address: %s" %self.getEmailAddress()
return people_string
Driver:
from PersonHierarchy import Person
import Address
def main():
p1 = Person("Nick", "D", "215-000-0000", Address("717 Test", "Test", "Texas", 75181), "000-00-0000", "test#test.com")
print(p1)
main()

How to return two values in Python

I have following code below.
class NameParser:
def __init__(self):
self.getName
def getName(self, name):
splitName = name.split(' ')
surname = splitName.pop()
for i in range(len(splitName)):
print('Name: %s' % splitName[i])
return('Surname: %s' % surname)
np = NameParser()
print(np.getName("ali opcode goren"))
# output: name: ali, name: opcode, surname: goren
How do i return two values? Like following code:
for i in range(len(splitName)):
return('Name: %s' % splitName[i])
return('Surname: %s' % surname)
# output: name ali: (error) i want all values name, name, surname
I want all values but just one output. How can I solve this problem?
Split: Split name by space and then do list comprehension again to remove the empty string from the list.
POP: get last item from the list by pop() method and assign it to surname variable.
Exception Handling: Do exception handling during pop process. If the input is empty then this will raise an IndexError exception.
string concatenate: Iterate every Item from the list by for loop and assign the value to user_name variable.
Concatenate surname in string again.
Display result.
Demo:
class NameParser:
def __init__(self):
pass
def getName(self, name):
#- Spit name and again check for empty strings.
splitName = [i.strip() for i in name.split(' ') if i.strip()]
#- Get Surname.
try:
surname = splitName.pop()
except IndexError:
print "Exception Name for processing in empty."
return ""
user_name = ""
for i in splitName:
user_name = "%s Name: %s,"%(user_name, i)
user_name = user_name.strip()
user_name = "%s Surname: %s"%(user_name, surname)
return user_name
np = NameParser()
user_name = np.getName("ali opcode goren abc")
print "user_name:", user_name
Output:
user_name: Name: ali, Name: opcode, Name: goren, Surname: abc
Try this:
class NameParser:
def __init__(self):
self.getName
def getName(self, name):
listy = [] # where the needed output is put in
splitName = name.split(' ')
for i in range(len(splitName)):
if i==(len(splitName)-1):#when the last word is reach
listy.append('Surname: '+ splitName[i])
else:
listy.append('Name: '+ splitName[i])
return listy
nr = NameParser()
print(nr.getName("ali opcode goren"))
# output: name: ali, name: opcode, surname: goren
whithout loop:
class NameParser:
def __init__(self):
self.getName
def getName(self, name):
listy = [] # where the needed output is put in
splitName = name.split(" ")
listy ="Name",splitName[0],"Name",splitName[1],"Surname",splitName[2]
return listy
nr = NameParser()
print(nr.getName("ali opcode goren"))
# output: name: ali, name: opcode, surname: goren
Try to use yield
class NameParser:
def __init__(self):
self.getName
def getName(self, name):
splitName = name.split(' ')
surname = splitName.pop()
for i in range(len(splitName)):
yield ('Name: %s' % splitName[i])
yield ('Surname: %s' % surname)
np = NameParser()
for i in (np.getName("ali opcode goren")):
print i
you can just do this:
def getName(self, name):
return name.split(' ')
It will return a tuple
def get_name(name):
return name.split(' ')
>>> get_name("First Middle Last")
['First', 'Middle', 'Last']
or you can try
class test():
map = {}
for i in range(10):
map[f'{i}'] = i
return map

Python Dict w/Array Values Passed as Params?

Alright so I have a dict with keys that point to an array of 5 values. These 5 values I pass to a class to sort out and feed me info etc.
Main
So, this works, but my querstion is is there a better way of exytracting the array to pass to the 'weapon' class, or do i just need to 'wepstats[0],wepstats[1]' etc? Or is there a better way of going about this? I'm all ears as Im only learning to do this stuff.
class Main():
def weaponDamage(self):
#print 15 * 2.22
wdb = WeaponDB()
wepstats = wdb.getWeaponStats('Sword')
wep = Weapon(wepstats[0],wepstats[1],wepstats[2],wepstats[3],wepstats[4])
wep2 = Weapon("Sword", 5, 55, 1.55, 2.1)
print wep
print wep2
s = sayThings()
greet = s.Say()
self.crit = wep.getDamageCrtRND()
self.scrit = wep.getDamageSCrtRND()
self.avg = wep.getDamageAvg()
self.high = wep.getDamageHigh()
self.low = wep.getDamageLow()
self.mod = wep.getDamageMod()
self.norm = wep.getDamageNrmRND()
self.name = wep.getWeaponName()
print greet
print "-----------"
print "Name: " + self.name
print "-----------"
print "High: %s" % self.high
print "Low : %s" % self.low
print "Avg : %s" % self.avg
print "Crit: %s" % self.crit
print "--------------------"
Dict
EDIT: Should I be making a DB of items in this manner in the first place? Is there a more logic method of doing this?
class WeaponDB():
"""Here be thine weapons of thy holy might"""
def __init__(self):
self.script = {
'None': "Error: No Weapon stats to get selected.",
'Sword': ("Sword", 5, 55, 1.55, 2.1),
}
def getWeaponStats(self, key = 'None'):
try:
return self.script[key]
except KeyError:
return self.script['None']
Class useing the values as parameters
class Weapon():
def __init__(self, name = "Stick", high = 1, low = 0, critMod = 1, scritMod = 2):
self.rng = randNum()
self.name = name
self.high = high
self.low = low
self.critMod = critMod
self.scritMod = scritMod
def getWeaponName(self):
return self.name
def getDamageHigh(self):
return self.high
def getDamageLow(self):
return self.low
def getDamageMod(self):
return self.critMod
def getDamageSMod(self):
return self.scritMod
etc...
If I understand well you can do something like this:
class Weapon:
def __init__( self, name = 'Stick', high = 1, low = 0 ):
self.name = name
self.high = high
self.low = low
wepstats = ( 'Sword', 5, 55 )
sword = Weapon( *wepstats )
Then if you check your attributes you get:
>>> sword.name
'Sword'
>>> sword.high
5
>>> sword.low
55
Using *wepstats you pass the entire tuple as arguments for your constructor.

Categories

Resources