class in python 3 not working as expected - python

I have started work on a program that will allow a user to easily take pictures with the raspberry pi camera. The problem I am having is the class I have created does not do what I expected. When the code is run there is no output, what should happen is the Picture_Name_Settings function should be run. I'm still new to classes so I am probably missing something simple and the tutorials I have read online do not give a solution to my problem. Below is my code:
import picamera, time
class CameraController:
def _init_(self):
pass
def Picture_Name_Settings(self, user_name, automatic_name, name_setting):
pic_name = input("To name the image input N\nTo use automatic naming input A ")
pic_name = pic_name.upper()
if pic_name == "N":
user_name = input("Please enter the name of what you want your image to be called ")
name_setting = 1
if pic_name == "A":
current_time = (time.strftime("%H:%M:%S"))
current_date = (time.strftime("%d:%m:%Y"))
automatic_name = "".join(("Image taken at ", current_time, " on the ", current_date, ".jpg"))
name_setting = 2
def Camera_Capture(self):
self.Picture_Name_Settings(user_name, automatic_name, name_settings)
if name_setting == 1:
picture_name = user_name
if name_setting == 2:
picture_name = automatic_name
camera = picamera.PiCamera()
camera.capture(picture_name)

Declare user_name, automatic_name and name_setting variables as instance variables and you should be fine
class CameraController:
def _init_(self):
pass
def Picture_Name_Settings(self):
pic_name = input("To name the image input N\nTo use automatic naming input A ")
pic_name = pic_name.upper()
if pic_name == "N":
self.user_name = input("Please enter the name of what you want your image to be called ")
self.name_setting = 1
if pic_name == "A":
current_time = (time.strftime("%H:%M:%S"))
current_date = (time.strftime("%d:%m:%Y"))
self.automatic_name = "".join(("Image taken at ", current_time, " on the ", current_date, ".jpg"))
self.name_setting = 2
def Camera_Capture(self):
self.Picture_Name_Settings()
if self.name_setting == 1:
picture_name = self.user_name
if self.name_setting == 2:
picture_name = self.automatic_name
camera = picamera.PiCamera()
camera.capture(picture_name)

Related

Object Oriented Programming with python issue with the list?

Code is not printing the multiple elements that I add to it. Instead it is just printing out the recently added element. can anyone guide me on this?
class bikes:
def __init__(self,make,name,model):
self.make = make
self.name = name
self.model = model
self.all_bikes = []
def total_bikes(self):
self.counter = 0
dict_bikes = {"Make": self.make,
"Name": self.name,
"Model": self.model}
self.all_bikes.append({self.counter : dict_bikes})
self.counter = self.counter + 1
def show_all_bikes(self):
print(self.all_bikes)
class user(bikes):
def __init__(self):
self.user_make = make = input("Enter the Company name: ")
self.user_name = name = input("Enter the Bike name: ")
self.user_model = model = input("Enter the Model name: ")
super().__init__(make,name,model)
bikes.total_bikes(self)
while True:
menu = input("Enter Add,View to Add a new bike and View all bikes: ")
if menu.upper() == "ADD":
add_bike = user()
elif menu.upper() == "VIEW":
add_bike.show_all_bikes()
else:
print("Invalid Command")
This construct
while True:
menu = input("Enter Add,View to Add a new bike and View all bikes: ")
if menu.upper() == "ADD":
add_bike = user()
elif menu.upper() == "VIEW":
add_bike.show_all_bikes()
else:
print("Invalid Command")
if ADD is choice then new instance of user class is created, which has empty all_bikes. You need to equip your class with seperate method for adding bike and __init__ and createdinstance of user class before entering while loop.

How do I import my own object in vs studio code?

I'm trying to import the Human object I created for my contact book program and im doing it in VS Studio Code but it gives me an error:
Import "Human" could not be resolved
I tried to make the program in pycharm instead and it imported just fine and I even finished the program. And while looking around for a solution for the VS Studio Code version, I found some stuff like adding
"python.autoComplete.extraPaths": ["./**"],
to my settings.json and I did and a few other things i found on google, but it nothing helped.
VS Studio Code:
from Human import Human
#from Contact_Book_Project.Human import Human # auto generated, Not sure how it is different but i do have these 2 classes in a folder called Contact_Book_Project
book = []
def main():
while (True):
choice = int(input("Press 1 to add someone to your Contact Book\n2 to remove someone from the book\n3 to find someone\n4 to list everyone\n5 to exit\n"))
if (choice == 5):
break
elif (choice == 1):
name = input("Name: ")
phoneNum = input("Phone Number: ")
address = input("Address: ")
person = Human(name, phoneNum, address)
addPerson(person)
def addPerson(person):
book.append(person)
if __name__ == "__main__":
main()
class Human:
def __init__(self, name, phone_Number, address):
self.Name = name
self.Phone_Number = phone_Number
self.Address = address
def getName(self):
return self.Name
def getPhoneNumber(self):
return self.Phone_Number
def getAddress(self):
return self.Address
PyCharm Code:
from Human import Human
book = []
def main():
while (True):
try:
choice = int(input(
"Press 1 to add someone to your Contact Book\n2 to remove someone from the book\n3 to find someone\n4 to "
"list everyone\n5 to exit\n"))
if (choice == 5):
break
elif (choice == 1):
name = input("Name: ")
phoneNum = input("Phone Number: ")
address = input("Address: ")
person = Human(name, phoneNum, address)
addPerson(person)
elif (choice == 2):
name = input("Enter name of person to remove: ")
temp = 0
for i in book:
if i.getName() == name:
book.pop(temp)
print(i.getName() + " removed.")
break
temp += 1
# elif (choice == 3):
# name = input("Enter name of person to check if they are in your contact book and retrieve their "
# "information: ")
#
# if name in book:
# temp = book.__getitem__(name)
# print(
# "Name: " + temp.getName() + "\nPhone Number: " + temp.getPhoneNumber() + "\nAddress: " + temp.getAddress())
# else:
# print(name + " does not exist in your contact book.")
elif (choice == 4):
for p in book:
print(
"Name: " + p.getName() + "\nPhone Number: " + p.getPhoneNumber() + "\nAddress: " + p.getAddress() + "\n")
except ValueError:
print("\nInvalid input.\n")
def addPerson(person):
book.append(person)
if __name__ == '__main__':
main()
both are using the same Human class. How can I fix this? Why is it throwing an error in VS Studio but work in Pycharm?
Maybe try directing VS Code to the exact location of the Human module:
import sys
sys.path.append('file path to Human.py') # Add file path to 'Human.py' here
from Human import Human

Class Attributes not updating in program

I am fairly new to coding on Python. In my code, I am trying to change the myPlayer.hp and myPlayer.sp values based on what the myPlayer.job is. But, for some reason, regardless of job, the HP and SP values are still 0 when I check them in the program. If you know how to change them, please let me know and thank you.
Here is the code that deals with my question:
class player:
def __init__(self):
self.name = ''
self.job = ''
self.hp = 0
self.sp = 0
self.pwr = 0
self.res = 0
self.agi = 0
self.smr = 0
self.wll = 0
self.status_effects = []
self.location = 'b2'
self.game_over = False
myPlayer = player()
def main_game_loop():
while myPlayer.game_over is False:
prompt()
def setup_game():
os.system('cls')
question1 = "Hello, what's your name?\n"
for character in question1:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
player_name = input("> ")
myPlayer.name = player_name
question2 = "Hello, what role do you want to play?\n"
question2added = "(You can play as a warrior, mage, or priest)\n"
for character in question2:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
for character in question2added:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.01)
player_job = input("> ")
valid_jobs = ['warrior', 'mage', 'priest']
if player_job.lower() in valid_jobs:
myPlayer.job = player_job
print("You are now a " + player_job + "!\n")
while player_job.lower() not in valid_jobs:
player_job = input("> ")
if player_job.lower() in valid_jobs:
myPlayer.job = player_job
print("You are now a " + player_job + "!\n")
if myPlayer.job == 'warrior':
myPlayer.hp = 25
myPlayer.sp = 0
elif myPlayer.job == 'mage':
myPlayer.hp = 15
myPlayer.sp = 20
elif myPlayer.job == 'priest':
myPlayer.hp = 20
myPlayer.sp = 15
Your code isn't necessarily incorrect, but there is a good chance for an error when the player enters their job.
You have the following code:
if player_job.lower() in valid_jobs:
That means that if the player enters Warrior you understand that they meant warrior. That is good. But when you assign the player's job you do the following:
myPlayer.job = player_job
That can cause a problem, since you aren't calling lower() on the job.
Instead, you likely want:
myPlayer.job = player_job.lower()
That way, when you look at the player's job to assign sp and hp it will match the lowercase strings you are comparing it to.

Entering a Changing Class Object into a List for Python

I'm trying to make a program that creates objects from another class I made and calls the class methods based on user input. The problem I'm having is that once a object is created I'm trying to enter that object into a dictionary, so I can compress it with pickle for later use. I'm having trouble trying to find the best way to append these class objects into a list when the name for the created objects are the same as the name variable I prompt from the user. The lines I am talking about are lines 34 to 41. I have so far change it to set the object named personObject to create a object and repeat if another user is created. It seems to work, I just feel there is a better way.
from budgetaccount import *
import pickle
import sys
class mainprogram:
def __init__(self):
self.account_list = {}
self.name = ""
def main(self):
grab_user()
endProgram = 0
while endProgram != 6:
print('Welcome to our monthly budget program\n')
print('1-Create a new account')
print('2-Exit')
selection = input("Enter your Selection: ")
if selection != "":
choice = int(selection)
if choice == 1:
self.create_user()
if choice == 2:
break
continue
name = self.account_list[0]
name.showSetBudgetLimits()
def create_user(self):
cancel = False
while (True):
self.name = input("Type your username: ")
name = self.name
income = float(input("Enter your income: "))
personObject = BudgetAccount(name, income)
personObject.setUserExspenseLimit()
self.account_list.append({
"%s"% (name) : personObject
})
cont = input("Want to add another? (Y/N)")
if cont == "N":
break
continue
print(self.account_list)
self.pickle_data1()
def pickle_data1(self): ###Pickle writes to userdata1.pickle from account_list###
pickle_out = open("userdata1.pickle", "wb")
pickle.dump(self.account_list, pickle_out)
pickle_out.close()
def grab_user():
pickle_in = open("E:/Python/Lib/idlelib/userdata1.pickle","rb")
account_list = pickle.load(pickle_in)
print(account_list)
print(account_list)
test = ihateThis()
test.main()

How to properly use __repr__ when two classes are involved

I am working on some Python code where I create a basic ATM. The issue I am having is I am not able to get the result that I want its printing "<'function Account.balance at 0x012CBC90>" Instead of the actual balance number. So far I have only tested using jsmith. Feel free to call out any other issues that may cause a problem later.
class Account:
def __init__(self,user,pin,balance):
self.user = user
self.pin = pin
self.balance = int(balance)
def get_user(self):
return self.user
def get_pin(self):
return self.pin
def balance(self):
return int(self.balance)
def setBalance(self,newBalance):
self.balance = newBalance
def __repr__(self):
return str(self.user) + " " + str(self.pin) + " " + str(self.balance)
class ATM:
def withdraw(self,Person,amount):
result = Person - amount
return result
def check(self,Person):
Person = Account.balance
return str(Person)
def transfer(self,id1,id2):
pass
def __str__(self):
return self
def main():
Chase = ATM()
Database = []
Teron_Russell = Account("trussell",1738,0)
Joe_Smith = Account("jsmith",1010,1350)
print(Teron_Russell)
Database.append(Teron_Russell)
Database.append(Joe_Smith)
print("Welcome to the ATM")
id = input("Please enter your user ID: ")
pin = input("Enter your pin: ")
chosen = ""
for i in Database:
print("Test1")
name = Account.get_user(i)
print(name)
checkPin = Account.get_pin(i)
print(checkPin)
if id == name and pin == checkPin:
chosen = i
choice = input("What would you like to do. (Type 'Check','Withdraw','Transfer': ")
if(choice == "Check" or "check"):
print(Chase.check(chosen))
# if(choice == "Withdraw" or "withdraw"):
# wAmount = eval(input("How much would you like to Withdraw: "))
# # Chase.withdraw(Account.balance,)
# elif(choice == "Check" or "check"):
# Chase.check()
# else:
# print("Invalid Choice!")
if __name__ == "__main__":
main()
You named a variable and a method the same name, so the interpreter is confused on which one to use. Change the name of either the method or variable balance and you won't have this problem. Additionally, this isn't java, and you shouldn't use classes for no reason. Since you aren't using any instance variables, it is pointless to have all of those methods inside that class.

Categories