I have been programming a piece of code to try and carry through a class from one function to another (the code is also broken in other ways but those aren't the important ones). The major problem if you define a class in the enter function it then gives the error:
exec("""print({}.Show())""".format(x))
File "<string>", line 1, in <module>
NameError: name (whatever I have called the class title) is not defined
in the tr function.
import pickle
import traceback
import sys
classtitles = []
class Customer(object):
def __init__(self):
try:
self.load()
print(self.customer)
except:
None
def init2(self,customer_name,home_address,telephone_number):
self.customer = customer_name
self.address = home_address
self.phone = telephone_number
print(self.customer)
classtitles.append(self.customer)
def carpet_amounts(self, carpet_type, grippers_bool):
self.type = carpet_type
self.grippers = grippers_bool
def price(self, size, perimeter):
self.size = size
self.perimeter = perimeter
self.price = 0
if self.type == "First":
self.price = float(5.99) * self.size
if self.type == "Monarch":
self.price = float(7.99) * self.size
if self.type == "Royal":
self.price = int(60) * self.size
price_add = float(22.5) * self.size
if self.grippers == True:
price_add += self.perimeter * float(1.10)
hours = 0
while size >= 16:
hours += 1
size -= 16
self.hours = hours
price_add += hours * 65
self.price += price_add
def Show(self):
print("show")
if self.grippers == True:
grips = "with"
else:
grips = "without"
return ("the size is {}m^2 and with a {} undercarpet and {} grippers, totalling more than {} hours of work is {}".format(self.size,self.type,grips,self.hours,self.price))
def save(self):
"""save class as self.name.txt"""
file = open('ClassSave.txt','wb')
file.write(pickle.dumps(self.__dict__))
file.close()
def load(self):
"""try load self.name.txt"""
file = open('ClassSave.txt','r')
datapickle = file.read()
file.close()
self.__dict__ = pickle.loads(dataPickle)
def loadf():
f = open('classnames.txt','r')
mylist = f.read().splitlines()
for x in mylist:
exec("""{} = Customer()""".format(mylist[0]))
customs()
def customs():
try1 = input("Would you like to 1. Enter a new customer. 2. View all the customers. 3. Delete an old customer")
if try1 == '1':
enter()
elif try1 == 'q':
sys.exit()
else:
tr()
def enter():
name = input("What is thr customers name (no space i.e. 'JoeBloggs')? ")
address = input("What is their address")
phonenumber = str("What is their phone number")
exec("""{} = Customer()""".format(name))
exec("""{}.init2("{}","{}","{}")""".format(name,name,address,phonenumber))
print(classtitles)
carpet_type = input("What type of carpet would they like ('First','Monarch','Royal')? ")
grips = str(input("Would they like grips (1 = yes, 2 = no)? "))
if grips == '1':
grips = True
else:
grips = False
exec("""{}.carpet_amounts("{}",{})""".format(name,carpet_type,grips))
size = int(input("What is the m^2 size of their carpet? "))
perimeter = int(input("What is the m perimeter of their carpet? "))
exec("""{}.price({},{})""".format(name,size,perimeter))
exec("print({}.Show())".format(name))
file2 = open('classnames.txt','w')
for x in classtitles:
file2.write(x)
file2.close()
exec("{}.save()".format(name))
customs()
def tr():
x = input("name")
print(x)
exec("""print({}.Show())""".format(x))
customs()
loadf()
Related
When I run my .py file, it quickly shows a blank black screen then disappears and does nothing. The script works fine in the editor though! The full code is down below, I know it could use some improvement but I'm just looking for answers to the blank screen for now. :) (The script is a simple genetic algorithm btw)
#!/usr/bin/python3
from fuzzywuzzy import fuzz
import random
import string
def error_msg():
print('\nSomethine went wrong!\nMake sure you typed the information correctly!')
mainF()
def mainF():
try:
while 7 == 7:
print()
stri = input('Enter string here: ')
gene = input('Enter number of generations here: ')
agen = input('Enter number of agents here: ')
muta = input('Enter chance of mutation here (0 - 1): ')
thre = input('Enter threshold here: ')
if stri == '' or gene == '' or agen == '' or thre == '' or muta == '' or stri.isdigit() or gene.isalpha() or agen.isalpha() or thre.isalpha() or muta.isalpha():
print('\nSomethine went wrong!\nMake sure you typed the information correctly!')
else:
ga(stri, len(stri), agen, gene, thre, muta)
except:
error_msg()
class Agent:
def __init__(self, length):
self.string = ''.join(random.choice(string.ascii_letters) for _ in range(length))
self.fitness = -1
def __str__(self):
return 'String: ' + str(self.string) + ', Fitness: ' + str(self.fitness) + '.'
def init_agents(population_p, length):
try:
population = int(population_p)
return [Agent(length) for _ in range(population)]
except:
error_msg()
def fitness(agents, in_str_p):
try:
in_str = in_str_p
for agent in agents:
agent.fitness = fuzz.ratio(agent.string, in_str)
return agents
except:
error_msg()
def selection(agents):
try:
agents = sorted(agents, key=lambda agent: agent.fitness, reverse=True)
print('\n'.join(map(str, agents)))
agents = agents[:int(0.2 * len(agents))]
return agents
except:
error_msg()
def crossover(agents, in_str_len_p, population_p):
try:
population = int(population_p)
in_str_len = in_str_len_p
offspring = []
for _ in range((population - len(agents)) // 2):
parent1 = random.choice(agents)
parent2 = random.choice(agents)
child1 = Agent(in_str_len)
child2 = Agent(in_str_len)
split = random.randint(0, in_str_len)
child1.string = parent1.string[0:split] + parent2.string[split:in_str_len]
child2.string = parent2.string[0:split] + parent1.string[split:in_str_len]
offspring.append(child1)
offspring.append(child2)
agents.extend(offspring)
return agents
except:
error_msg()
def mutation(agents, in_str_len_p, mutation_chance_p):
try:
mutation_chance = float(mutation_chance_p)
in_str_len = in_str_len_p
for agent in agents:
for idx, param in enumerate(agent.string):
if random.uniform(0.0, 1.0) <= mutation_chance:
agent.string = agent.string[0:idx] + random.choice(string.ascii_letters) + agent.string[idx+1:in_str_len]
return agents
except:
error_msg()
def ga(in_str_p, in_str_len_p, population_p, generations_p, threshold_p, mutation_chance_p):
mutation_chance = mutation_chance_p
threshold = int(threshold_p)
population = population_p
generations = int(generations_p)
in_str = in_str_p
in_str_len = in_str_len_p
agents = init_agents(population, in_str_len)
for generation in range(generations):
print('Generation: ' + str(generation))
agents = fitness(agents, in_str)
agents = selection(agents)
agents = crossover(agents, in_str_len, population)
agents = mutation(agents, in_str_len, mutation_chance)
if any(agent.fitness >= threshold for agent in agents):
print('Threshold met!')
mainF()
if __name__ == '__main__':
mainF()
I've started trying to learn Python after working with Java for the past year and decided to work on a couple class projects I've done and to write them in Python. I am getting an AttributeError at line 102, stating my super object has no attribute 'area'.
I've looked through different posts of how it's done, and I can't seem to figure out why this isn't working correctly for me after following other solutions.
It's a simple program that takes in input from the user, parses it, then depending on the shape type, will call the methods of the appropriate object type, then calculates and prints it out. For example, an input would be "R 3/4 5-7", supposed to weigh 8.37, or "P 1/4 5-6 2-3", supposed to weigh 126.07.
import math
class Shipment:
_weight = 0
def weight(self):
return self._weight
def frac_in_feet(self, frac):
thick_frac = frac.replace('/', "")
print("number is: ", thick_frac)
numerator = int(thick_frac[0])
denominator = int(thick_frac[1])
fraction_of_an_inch = numerator / denominator
return self.in_feet(0, fraction_of_an_inch)
def feet_and_inches_in_feet(self, feet_and_inches):
a = feet_and_inches.replace('-', "")
print("number is: ", a)
feet = int(a[0])
inches = int(a[1])
return self.in_feet(feet, inches)
def in_feet(self, feet, inches):
inches /= 12
print(feet + inches)
return feet + inches
def get_value_in_feet(self, str):
i = str.find('/')
j = str.find('-')
if i == -1:
value = self.feet_and_inches_in_feet(str)
if j == -1:
value = self.frac_in_feet(str)
return value
def add_item(self, quantity, description):
desc_values = description.replace(" ", "")
values = []
shape_letter = desc_values[0]
i = 1
j = 4
for r in range(int(len(desc_values) / 3)):
print("r is: ", r)
values.append(self.get_value_in_feet(desc_values[i:j]))
i += 3
j += 3
if shape_letter == 'P':
if len(values) != 3:
raise ValueError("Plate needs three dimensions. ")
shape = Plate(values[0], values[1], values[2])
elif shape_letter == 'R':
if len(values) != 2:
raise ValueError("Rod needs two dimensions")
shape = Rod(values[0], values[1])
else:
raise ValueError("Shape letter ", shape_letter, " not recognized.")
self._weight += quantity * shape.weight()
return shape
class SteelShape:
_length = 0
_weight = 0
def length(self, length):
_length = length
def length(self):
return self._length
def weight(self, weight):
self._weight = weight
def weight(self):
return self._weight
class CalcShape(SteelShape):
_area = 0
def area(self, area):
self._area = area
def weight(self):
return self._area * self.length() * 489
class Rod(CalcShape):
def __init__(self, diameter, length):
radius = diameter / 2
super(CalcShape, self).area(math.pi * radius**2)
super(CalcShape, self).length
class Plate(CalcShape):
def __init__(self, thick, width, length):
super(CalcShape, self).area(thick * width)
super(SteelShape, self).length(length)
values = []
shipment = Shipment()
shape = SteelShape()
line = input("Enter shape and dimensions: ")
shape = shipment.add_item(1, line)
if isinstance(shape, Plate):
print("Plate weighs ", shape.weight())
elif isinstance(shape, Rod):
print("Rod weighs ", shape.weight())
print("Total shipment weight: ", shipment.weight())
# R 3/4 5-7: supposed to weigh 8.37
# P 1/4 5-6 2-3: supposed to weigh 126.07
I think replacing the super and instead using staticmethod is a better choice. See here:
https://stackoverflow.com/a/735978/10416716
Hope this helps.
import sys
import os.path
class Juvenile(object):
def createJuv(self, pop, rate):
self.pop = pop
self.rate = rate
def displayJuvpop(self):
return self.pop
def displayjuvRate(self):
return self.rate
class Adult(object):
def createAd(self, pop, rate, brate):
self.pop = pop
self.rate = rate
self.brate = brate
def displayAdpop(self):
return self.pop
def displayAdRate(self):
return self.rate
def displayBirthrate(self):
return self.brate
class Senile(object):
def createSe(self, pop, rate):
self.pop = pop
self.rate = rate
def displaySepop(self):
return self.pop
def displaySerate(self):
return self.rate
a = Juvenile()
b = Adult()
c = Senile()
`enter code here`pop_model = raw_input("Enter the number of generations: ")
`enter code here`pop_model = int(pop_model)
newjuv = 0
newsen = 0
newadu = 0
def menu():
This = True
while This == True:
print("1) Enter Generation 0 values")
print("2) Display Generation 0 values")
print("3) Run the model")
print("4) Export data")
print("5) Quit")
decision = raw_input("")
if decision == "1":
Gen0values()
elif decision == "2":
display()
elif decision == "3":
run()
elif decision == "4":
export()
elif decision == "5":
sys.exit()
def run():
print("Juvenile" + " " + "Adult" + " " + "Senile")
for i in range(0, pop_model):
newjuv = b.displayAdpop()* b.displayBirthrate()
newsen = b.displayAdpop() * b.displayAdRate()
newadu = a.displayJuvpop() * a.displayjuvRate()
print(i + 1,newjuv, newadu,newsen)
a.displayJuvpop() = newjuv
b.displayAdpop() = newsen
c.displaySepop() = newadu
def Gen0values():
a.createJuv(float(raw_input("Enter the juvenile population: ")), float(raw_input("Enter the Juvenile survival rate: ")))
b.createAd(float(raw_input("Enter the Adult population: ")), float(raw_input("Enter the Adult survival rate: ")), float(raw_input("Enter the birth rate: ")))
c.createSe(float(raw_input("Enter the Senile population: ")), float(raw_input("Enter the Senile survival rate: ")))
menu()
The error is coming up here:
def run():
print("Juvenile" + " " + "Adult" + " " + "Senile")
for i in range(0, pop_model):
newjuv = b.displayAdpop()* b.displayBirthrate()
newsen = b.displayAdpop() * b.displayAdRate()
newadu = a.displayJuvpop() * a.displayjuvRate()
print(i + 1,newjuv, newadu,newsen)
a.displayJuvpop() = newjuv
b.displayAdpop() = newsen
c.displaySepop() = newadu
The error comes up with "Can't assign to function call, line 60". Due to stack overflow's code to text limit, I've removed parts of the program that are irrelevant, like exporting the data and displaying the values.
Ps: This isn't an indentation error, copying and pasting somewhat disrupted it.
Your display*pop() functions return a value, not a variable. You can't assign to that function result. Just assign directly to the attributes:
a.pop = newjuv
b.pop = newsen
c.pop = newadu
I have an employee class which has an init method that reads an employees record in from a file. I also have an employees class which has an init_ method that attempts to read in all of the employee records.
I am having trouble with init for the employees class. Here is my code:
class EmployeeList():
records=[]
def __init__(self):
with open(database) as fp:
emp=employee(fp)
while (emp.id > 0):
print(emp)
self.records.append(emp)
emp=employee(fp)
The print(emp) is there for error checking, it shows that the records are being read in properly. When the EOF is reached, the init method for the employee sets the id to 0 and the name of the employee to "". I have two problems:
After the loop, all of the employees in employees.records are the same - id 0 and blanks for names. I am assuming that that emp is not creating a new instance each time it is called, and so all of the employees are being set to that one instance of emp, the very last one from when EOF is reached.
I doubt my code is "Pythonesque"; suggestions for improvement are welcome.
P.S. database is globally defined to the file name.
The entire code is here, sorry about the length:
class employee:
count = 0
def __init__(self,f=None):
if (f==None): # a user is inputting the employee
self.lastname = input("Employees last name:")
while type(self.lastname)!=type("1"):
print("Your input needs to be a name\n")
self.lastname = input("Employees last name:")
self.firstname = input("Employees first name:")
while type(self.firstname)!=type("1"):
print("Your input needs to be a name\n")
self.firstname = input("Employees first name:")
self.payrate = float(input("Employees pay rate:"))
while type(self.payrate)!=type(0.0):
print("Your input needs to be a pay rate\n")
self.payrate = float(input("Employees pay rate:"))
employee.count = employee.count + 1
self.id = employee.count
else: # the employee is being read in from the database and f is a file pointer
# read in an employee record and return false for end of file.
checkEOF = f.readline().rstrip('\r\n') #check for end of file
if (checkEOF != ""):
employee.id = int(checkEOF)
employee.firstname = f.readline().rstrip('\r\n')
employee.lastname = f.readline().rstrip('\r\n')
employee.payrate = float(f.readline().rstrip('\r\n'))
else:
employee.id = 0
employee.firstname = " "
employee.lastname = " "
employee.payrate = 0.0
def __hash__(self):
return hash(self.id)
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.id == other.id
return NotImplemented
def __str__(self):
return "Employee " + str(self.id) + " is "+self.firstname + " "+self.lastname+" and their pay rate is "+str(self.payrate)+"\n"
def __lt__(self, other):
if (self.lastname < other.lastname):
return True
elif (self.lastname > other.lastname):
return False
else: #same last names
if (self.firstname < other.firstname):
return True
elif (self.firstname > other.firstname):
return False
else: #same names
if (self.id < other.id):
return True
else: # note that ids cannot be the same
return False
def __gt__(self, other):
if (self.lastname > other.lastname):
return True
elif (self.lastname < other.lastname):
return False
else: # Same last names
if (self.firstname > other.firstname):
return True
elif (self.firstname > other.firstname):
return False
else: # Same names
if (self.id > other.id):
return True
else: # note that ids cannot be the same
return False
def payraise(self,payraise):
self.payrate = self.payrate+payraise
def saveemployee(self,fp):
fp.write(str(self.id)+"\n")
fp.write(self.firstname+"\n")
fp.write(self.lastname+"\n")
fp.write(str(self.payrate)+"\n")
class EmployeeList():
records=[]
def __init__(self):
with open(database) as fp:
emp=employee(fp)
while (emp.id > 0):
print(emp)
self.records.append(emp)
emp=employee(fp)
def __str__(self):
employeesprint = ""
for emp in self.records:
employeesprint = employeesprint + str(emp)
return employeesprint
def save(self):
self.records.sort()
with open(database,"w+") as fp:
fp.seek(0)
for emp in self.records:
emp.saveemployee(fp)
def menu():
print("\n")
print(choices[0]+". Add another employee")
print(choices[1]+". Print employees")
print(choices[len(choices)-1]+". Quit")
print("\n")
employees = EmployeeList()
choices = ["A","B","C"]
ch = "N"
while (ch != choices[len(choices)-1]):
menu()
ch=input("Make your choice ")
while not (ch in choices):
menu()
ch=input("Make your choice ")
if (ch == choices[0]):
employees.records.append(employee())
employees.save()
if (ch == choices[1]):
print(employees)
Sample output: You can see the two employees correctly being printed as they are read in:
Employee 1 is jane bob and their pay rate is 1.0
Employee 2 is jim bob and their pay rate is 3.4
A. Add another employee
B. Print employees
C. Quit
Make your choice B
Employee 0 is and their pay rate is 0.0
Employee 0 is and their pay rate is 0.0
your code:
if (checkEOF != ""):
employee.id = int(checkEOF)
employee.firstname = f.readline().rstrip('\r\n')
employee.lastname = f.readline().rstrip('\r\n')
employee.payrate = float(f.readline().rstrip('\r\n'))
else:
employee.id = 0
employee.firstname = " "
employee.lastname = " "
employee.payrate = 0.0
change 'employee' to 'self', 'employee' is the name of the class.
I need help with an elevator simulator in Python and I don't have much experience. There should be a user entered amount of customers that have randomized start and destination floors. Right now I'm just coding the simple strategy of the elevator going all the way to the top, and then back to the bottom. When I run my code, the program infinitely loops. I can't figure out why. Also, I'm not sure how to code my building's output method, which I want to display which customers had which floors and how many floors the elevator visited. Thanks for your help.
import random
class Elevator(object):
def __init__(self, num_of_floors, register_list, direction = "up", cur_floor=1):
self.total_floors = num_of_floors
self.reg_list = register_list
self.floor = cur_floor
self.direct = direction
def move(self):
"""Moves the elevator one floor"""
if self.total_floors == self.floor:
self.direct = "down"
if self.direct == "up":
self.floor += 1
else:
self.floor -= 1
def register_customer(self, customer):
self.reg_list.append(customer)
def cancel_customer(self, customer):
self.reg_list.remove(customer)
class Building(object):
def __init__(self, num_of_floors, customer_list, elevator):
self.total_floors = num_of_floors
self.customers = customer_list
def run(self):
while elevator.floor != 0:
for customer in self.customers:
if elevator.floor == customer.on_floor:
elevator.reg_list.append(customer)
customer.indicator = 1
elif elevator.floor == customer.going_floor:
elevator.reg_list.remove(customer)
customer.indicator = 0
customer.fin = 1
elevator.move()
def output(self):
pass
class Customer(object):
def __init__(self, ID, num_of_floors, cur_floor=0, dst_floor=0, in_elevator=0, finished=0):
self.ident = ID
self.indicator = in_elevator
self.fin = finished
cur_floor = random.randint(1, num_of_floors)
self.on_floor = cur_floor
dst_floor = random.randint(1, num_of_floors)
while dst_floor == cur_floor:
dst_floor = random.randint(1, num_of_floors)
self.going_floor = dst_floor
customer_count = int(input("How many customers are in the building?: "))
floor_count = int(input("How many floors does the building have?: "))
cus_list = []
for i in range(1, customer_count+1):
cus_list.append(Customer(i, floor_count))
elevator = Elevator(floor_count, cus_list)
building = Building(floor_count, cus_list, elevator)
Your problem lies here:
def run(self):
while elevator.floor != 0:
print(elevator.floor)
for customer in self.customers:
print(customer)
if elevator.floor == customer.on_floor:
elevator.reg_list.append(customer)
customer.indicator = 1
elif elevator.floor == customer.going_floor:
elevator.reg_list.remove(customer)
customer.indicator = 0
customer.fin = 1
elevator.move()
When you do elevator.reg_list.append(customer), you are re-appending the customer to the list, increasing it size (self.customers is also a reference to this same list) so the "for customer in self.customers" loops forever.
Lets follow "cus_list" :
elevator = Elevator(floor_count, cus_list)
building = Building(floor_count, cus_list, elevator)
class Building(object):
def __init__(self, num_of_floors, customer_list, elevator):
self.total_floors = num_of_floors
self.customers = customer_list
class Elevator(object):
def __init__(self, num_of_floors, register_list, direction = "up", cur_floor=1):
self.total_floors = num_of_floors
self.reg_list = register_list # <-------- THIS IS "cus_list" reference
Finally in class Building:
elevator.reg_list.append(customer)
elevator is a global variable here created outside the scope of the class FYI.
A fix may be as follows
The elevator starts out empty right?
class Elevator(object):
def __init__(self, num_of_floors, register_list, direction = "up", cur_floor=1):
self.total_floors = num_of_floors
self.reg_list = []