How to assign a class with an if statement in Python - python

I have two different devices I use in the lab. I would like to use input from command line to change which device I am using. To elaborate, I would like to type in the name of the device and a variable is defined by that name inside a if statement. Currently when I try the below code I get:
AttributeError: class temp_class has no attribute 'get_int'
What am I doing wrong
from classA import*
from classB import*
from temp_class import*
tempC = temp_class()
print tempC
user_input = raw_input()
print user_input
if (user_input == "a") :
tempC.__del__()
tempC = class_a(5)
if (user_input == 'b') :
tempC = class_b(5)
print temp_class
tempC.set_int(5)
print temp_class.get_int()
Output of code:
What is inside temp_class
class temp_class:
def __init__(self):
self.num = 8
What is inside classA
class class_a(object):
def __init__(self, int):
self.num = self.set_int(int)
def set_int(self, int):
self.num = int
def get_int(self):
return self.num
what is inside class_b
class class_b:
def __init__(self):
self.num = 8

There is a lot of trouble with the code you've shared. I'll try to simplify it:
# prog.py
from device_a import DeviceA
from device_b import DeviceB
user_input = raw_input() # use input() if you have python3
if (user_input == "a") :
# no need to create an initial "temp" instance or to delete it
tempC = DeviceA(5)
elif (user_input == 'b') :
tempC = DeviceB() # DeviceB doesn't take any parameters
# tempC can either be a DeviceA or DeviceB, but both need to have the same methods defined
try:
tempC.set_int(5) # this will fail for DeviceB because it has no set_int method
except: # this should have a more specific exception type
pass
print tempC.get_int() # note that this is the name of the variable, not the class
# device.py
class Device(object):
def __init__(self, num):
self.num = num
def get_int(self):
return self.num
# device_a.py
from device import Device
class DeviceA(Device):
def __init__(self, num): # int is a builtin function, so it shouldn't be used as a parameter name
super(DeviceA, self).__init__(num)
def set_int(self, num):
self.num = num
# device_b.py
from device import Device
class DeviceB(Device):
def __init__(self):
super(DeviceB, self).__init__(8)
# no set_int, as this one seems to be fixed in your example

Last night I figure out how to fix my problem. Below is what I am now using.
obj_dic = {}
print obj_dic
print("a for class a for class b")
user_input = raw_input(":> ")
if user_input == 'a':
obj_dic = {'a':class_a()}
else:
obj_dic = {'b':class_b()}
tempC = obj_dic.get(user_input)
print tempC.get_int()
print tempC

Related

How to make sure that no other instances have the same name from a class

class Satellite:
def __init__(self, message):
print(message)
self.name = input("name: ").title()
self.lbs = int(input("lbs: "))
self.speed = int(input("speed: "))
lstSat = []
e= input("Would you like to create satellites? If yes, type O. If not, type another letter: ").lower()
i=0
while e=="o":
lstSat.append(Satellite("Info for satellite "+str(i+1)))
i+=1
e= input("Type O to create another satellite: ").lower()
Hello,
How can I make sure that 2 Satellites cannot be the same?
Please don't ask for user input during class construction. Much better to acquire the values elsewhere then use a straightforward constructor based on the user's input values.
In order to determine repetition, you need to override the eq dunder method.
Try this:
class Satellite:
def __init__(self, name, lbs, speed):
self._name = name
self._lbs = lbs
self._speed = speed
def __eq__(self, other):
if isinstance(other, str):
return self._name == name
if isinstance(other, type(self)):
return self._name == other._name
return False
def __str__(self):
return f'Name={self._name}, lbs={self._lbs} speed={self._speed}'
lstSat = []
PROMPT = 'Would you like to create satellites? If yes, type O. If not, type another letter: '
while input(PROMPT) in 'Oo':
name = input('Name: ').title()
if name in lstSat:
print(f'{name} already in use')
else:
lbs = int(input('lbs: '))
speed = int(input('Speed: '))
lstSat.append(Satellite(name, lbs, speed))
for satellite in lstSat:
print(satellite)
I would go for iteration in list and check names with every satellite
...
while e=="o":
satellite = Satellite("Info for satellite " + str(i+1))
if check_reapeated_name(lstSat, satellite.name): # see definition of function bellow
lstSat.append(satellite)
else:
# here do some output or error handling
...
...
and the definition of check_reapeated_name() would be something like this:
def check_reapeated_name(lstSat, satellite_name):
for i in lstSat:
if i.name == satellite_name:
return False
return True

I need to figure out how to save the user input as the new variables, not sure what to do from here

#I need to figure out how to save the user input as the new variables, not sure what to do from here.
class Person:
def __init__(self):
#I'm supposed to have the object set to these generic names at first and then after the prompt function they need to be updated.
self.name = 'anonymous'
self.b_year = 'unknown'
def prompt(self):
print('Please enter the following:')
self.name = input('Name: ')
self.b_year = input('Year: ')
b = Book()
b.prompt()
def display(self):
print(f'Author:\n{self.name} (b. {self.b_year})\n')
class Book:
def __init__(self):
self.title = 'untitled'
self.publisher = 'unpublished'
def prompt(self):
self.title = input('Title: ')
self.publisher = input('Publisher: ')
def display(self):
print(f'\n{self.title}\nPublisher:\n{self.publisher}')
p = Person()
`enter code here`p.display()
def main():
p = Person()
b = Book()
b.display()
p.prompt()
b.display() #right here I need it to display the new information
if __name__ == '__main__':
main()
Two things you need to do here. First of all you need to initialize your variables in your Person class. Second of all I don't understand what the point of creating objects in a class and then doing the same outside of the class. I suggest taking the following code and modifying it to your likings. Additionally I reorganized the way you call your methods. First you prompt the user with all the necessary questions, then display them all together.
class Person:
def __init__(self):
self.name = None
self.b_year = None
def prompt(self):
print('Please enter the following:')
self.name = input('Name: ')
self.b_year = input('Year: ')
def display(self):
print(f'Author:\n{self.name} (b. {self.b_year})\n')
class Book:
def __init__(self):
self.title = 'untitled'
self.publisher = 'unpublished'
def prompt(self):
self.title = input('Title: ')
self.publisher = input('Publisher: ')
def display(self):
print(f'\n{self.title}\nPublisher:\n{self.publisher}')
def main():
p = Person()
b = Book()
b.display()
p.display()
p.prompt()
b.prompt()
b.display()
p.display()#right here I need it to display the new information
if __name__ == '__main__':
main()
output
untitled
Publisher:
unpublished
Author:
None (b. None)
Please enter the following:
Name: a
Year: b
Title: c
Publisher: d
c
Publisher:
d
Author:
a (b. b)
I'm not designer so you don't have to go with my idea, but IMO, don't add \n like this '\n{self.title}\nPublisher:\n{self.publisher}'. It looks a bit weird in the output.
You create one Book in the main function, and then another Book inside the Person.prompt method. They aren't the same Book - you have two!
You need to decide if a book belongs within a person, or whether they are two top level objects that may have a relationship. From a "real world" perspective, I don't think a person should automatically have a book associated with them. Perhaps you could create a Book and then pass to the Person constructor...

python 3 error RuntimeError: super(): no arguments

Why do I get this error? Can someone solve this problem for me? I tried to call the display function from class project in Progress.display() or anybody has other solution on how to display the users input?
And how can I input Stages class and Progress class at the same time ? thanks for the helpp
super().display()
RuntimeError: super(): no arguments
Here's the code
class Project:
def __init__(self, name="", job="", **kwargs):
super().__init__(**kwargs)
self.name = name
self.job = job
def display():
print("name: ", (self.name))
print("job: ", (self.job))
#staticmethod
def prompt_init():
return dict(name=input("name: "), job=input("job: "))
class Stages(Project):
def __init__(self, stages="", **kwargs):
super().__init__(**kwargs)
self.stages = stages
def display(self):
super().display()
print("stages: ", (self.stages))
#staticmethod
def prompt_init():
parent_init = Project.prompt_init()
choice = None
while choice not in (1, 2, 3, 4, 5, 6):
print("Insert your stage now: ")
print("1. Planning")
print("2. Analysis")
print("3. Design")
print("4. Implementation")
print("5. Testing")
print("6. Release")
choice = input("enter your choice: ")
choice = int(choice)
if choice == 1:
stages = "Planning"
elif choice == 2:
stages = "Analysis"
elif choice == 3:
stages = "Design"
elif choice == 4:
stages = "Implementation"
elif choice == 5:
stages = "Testing"
elif choice == 6:
stages = "Release"
else:
print("no such input, please try again")
print(name)
print(stages)
class Progress(Project):
def __init__(self, progress="", **kwargs):
super().__init__(**kwargs)
self.progress = progress
def display(self):
super().display()
print("progress: ", (self.progress))
#staticmethod
def prompt_init():
parent_init = Project.prompt_init()
choice = None
while choice not in (1, 2, 3, 4):
print("1. 25%")
print("2. 50%")
print("3. 75%")
print("4. 100%")
choice = input("enter your choice[1-4]: ")
choice = int(choice)
if choice == 1:
progress = "25%"
elif choice == 2:
progress = "50%"
elif choice == 3:
progress = "75%"
elif choice == 4:
progress = "100%"
else:
print("no such input, please try again")
print(progress)
parent_init.update({"progress": progress})
return parent_init
class A(Stages, Progress):
def prompt_init():
init = Stages.prompt_init()
init.update(Progress.prompt_init())
return init
prompt_init = staticmethod(prompt_init)
class New:
type_map = {("stages", "progress"): A}
def add_project_test(self, name, job, stages):
init_args = Project.prompt_init()
self.project_list.append(Project(**init_args))
def __init__(self):
self.project_list = []
def display_project():
for project in self.project_list:
project.display()
print()
def add_progress(self):
init_args = Progress.prompt_init()
self.project_list.append(Progress(**init_args))
def add_project(self):
ProjectClass = self.type_map[A]
init_args = ProjectClass.prompt_init()
self.property_list.append(ProjectClass(**init_args))
my_list = New()
my_list.add_progress()
my_list.display_project()
Not 100% solution to the answer, but same error. Posted with love for Googlers who have the same issue as me.
Using Python 3, I got this error because I forgot to include self in the method. Simple thing, but sometimes the most simple things trip you up when you're tired.
class foo(object):
def bar(*args):
super().bar(*args)
=> RuntimeError: super(): no arguments
Remember to include your self
class foo(object):
def bar(self, *args):
super().bar(*args)
Not really an answer for this question, but I got this same error when trying to call super while in a pdb shell and ended up going down a rabbit hole trying to figure it out. You need to add the parent class you want to call super on and self to the call in order for it to run - super(<ParentClass>, self) - in pdb. Or at least just know that super won't work as expected in pdb. I didn't really need to call it there, but it blocked me from figuring out why something else wasn't working.
Every time you use super() in a method, you need to be in an instance method or a class method. Your staticmethods don't know what their superclasses are. Observe:
class Funky:
def groove(self):
print("Smooth")
#staticmethod
def fail():
print("Ouch!")
#classmethod
def wail(cls):
print("Whee!")
class Donkey(Funky):
def groove(self):
print(super())
#staticmethod
def fail():
try:
print(super())
except RuntimeError as e:
print("Oh no! There was a problem with super!")
print(e)
#classmethod
def wail(cls):
print(super())
a_donkey = Donkey()
a_donkey.groove()
a_donkey.fail()
a_donkey.wail()
Outputs:
<super: <class 'Donkey'>, <Donkey object>>
Oh no! There was a problem with super!
super(): no arguments
<super: <class 'Donkey'>, <Donkey object>>
Here's your code, debugged and with some extra functionality and tests:
class Project:
def __init__(self, name="", job="", **kwargs):
super().__init__(**kwargs)
self.name = name
self.job = job
def display(self):
print("name: ", self.name)
print("job: ", self.job)
#staticmethod
def prompt_init():
return dict(name=input("name: "), job=input("job: "))
class Progress(Project):
def __init__(self, progress="", **kwargs):
super().__init__(**kwargs)
self.progress = progress
def display(self):
super().display()
print("progress: ", self.progress)
#staticmethod
def prompt_init():
parent_init = Project.prompt_init()
progress = input("your progress: ")
parent_init.update({
"progress": progress
})
return parent_init
class New:
def __init__(self):
self.project_list = []
def display_project(self):
for project in self.project_list:
project.display()
print()
def add_project(self):
init_args = Project.prompt_init()
self.project_list.append(Project(**init_args))
def add_progress(self):
init_args = Progress.prompt_init()
self.project_list.append(Progress(**init_args))
my_list = New()
my_list.add_project()
my_list.add_progress()
my_list.display_project()
You might not have to use super() at all, just reference the super class directly. For example, I was writing a Django test like this one, but in my case the AnimalTestCase was inheriting a ParentTestCase. I wanted the fixture property in AnimalTestCase to use all the same fixtures in ParentTestCase, and add a couple more. But calling super() never worked. In the end, I realized that I could reference ParentTestCase as it was.
fixtures = ParentTestCase.fixtures + ['more']
class ParentTestCase(TestCase):
fixtures = ['bacteria', 'fungus', 'stalagtites', 'stalagmites']
def setUp(self):
# Test definitions as before.
call_setup_methods()
class AnimalTestCase(ParentTestCase):
fixtures = ParentTestCase.fixtures + ['vertebrata', 'invertebrate']
def test_fluffy_animals(self):
# A test that uses the fixtures.
call_some_test_code()

Beginner Python Classes - changing the attribute value with user input

I am just learning classes in Python and for the past day I am stuck with the below.
I am trying to use a user input (from the main() function) to change the value of an attribute in the class.
I have been throught the #property and #name.setter methods that allow you to change the value of a private attribute.
However I am trying to find out how you can use user input to change the value of an attribute that is not private.
I came up with the below but it does not seem to work. The value of the attribute remains the same after I run the program. Would you have any ideas why?
class Person(object):
def __init__(self, loud, choice = ""):
self.loud = loud
self.choice = choice
def userinput(self):
self.choice = input("Choose what you want: ")
return self.choice
def choiceimpl(self):
self.loud == self.choice
def main():
john = Person(loud = 100)
while True:
john.userinput()
john.choiceimpl()
print(john.choice)
print(john.loud)
main()
In choiceimpl you are using == where you should use =.
Like stated before, you are using a comparison with == instead of the =.
Also you are returning self.choice in userinput as a return value, but never use it, because you set self.choice equal to input.
Shorter example:
class Person:
def __init__(self, loud):
self.loud = loud
def set_loud(self):
self.loud = input("Choose what you want: ")
def main():
john = Person(100)
while True:
john.set_loud()
print(john.loud)
main()
1) Change: '=='(comparison operator) to '='(to assign)
2) Inside class:
def choiceimpl(self,userInp):
self.loud = self.userInp
3) Outside class
personA = Person(loud) # Create object
userInp = raw_input("Choose what you want: ") # Get user input
personA.choiceimpl(userInp) # Call object method

Python Error: 'finalStore' object has no attribute 'name'

I'm working with Inheritance in python but i'm getting an error i don't know how to fix, 'finalStore' object has no attribute 'marone'. I get this when i try create an object.
from ClassFile import studStore
class finalStore (studStore):
grandAve = 0
numStu = 0
def __init__(self, name, marone, martwo, marthree, marfour, corone, cortwo, corthree, corfour):
studStore.__init__(self, name, marone, martwo, marthree, marfour)
self.corone = corone
self.cortwo = cortwo
self.corthree = corthree
self.corfour = corfour
finalStore.numStu += 1
self.holder = finalStore.numStu
self.average = (marone + martwo + marthree + marfour)/4
finalStore.grandAve += self.average
self.storit = finalStore.grandAve
My initializing for the child class
class studStore:
def __init__(self, name, marone, martwo, marthree, marfour):
self.newname = name
self.Ave = 0
self.marone = marone
self.martwo = martwo
self.marthree = marthree
self.marfour = marfour
And the initializing for the parent class. My main line is just a loop where i create multiple objects for but it errors on this line:
listIn.append(finalStore(name, gradeone, gradetwo, gradethree, gradefour, courseOne, courseTwo, courseThree, courseFour))
I'm not sure what the error is but I have a similar program that works, I'm just not using the from * import *
I'm outputting it like this
for i in range (0,len(listIn)):
print(str(listIn[i].returnName()).ljust(20," "), end = " ")
print(str(listIn[i].returnOne()).ljust(20, " "))
print(str(listIn[i].returnTwo()).ljust(20, " "))
print(str(listIn[i].returnThree()).ljust(20, " "))
print(str(listIn[i].returnFour()).ljust(20, " "))
Your call to the super class's init function is incorrect. Here is how you should do it:
class finalStore(studStore):
def __init__(self, name, ...):
super(finalStore, self).__init__(name, marone, ...)

Categories