I'm trying to use a class to store a user input but seem to be running into some issues. I would normally just use input() but the class I'm taking is asking us to build a class that represents an object of interest. Below is the code that I've developed so far but I feel like I'm making a class for the sake of making a class. Am I missing something here?
import requests
class Requirement:
def __init__(self, address):
self.address = input("enter address here")
return address
address = input('Enter Address')
loc = Nominatim(user_agent="GetLoc")
getLoc = loc.geocode({address})
# printing address
print(getLoc.address)
# printing latitude and longitude
print("Latitude = ", getLoc.latitude, "\n")
print("Longitude = ", getLoc.longitude)```
Related
I apologise - this is my first attempt at using pytest or any python testing library, but I have done a small amount of JUnit so am vaguely familiar with the principles.
Basically, the class I want to test has a couple of member variables that I want to stub. Specifically, I only need some customer details. I access this under the OrderController class in its class variable 'orders' (a list of dictionaries with purchase id as key and order objects as values). When I get this order object I would like to access the customer attribute which is comprised of their name and address - this address attribute is another member variable.
Below is the address_label.py module (I'm sorry about the comments - it is for University)
"""
--------------------------------------------------------------------------------------------
title : address_label.py
description : Formats order data for creation of address labels in the pdf.py module.
python_version : 3.7.9
--------------------------------------------------------------------------------------------
"""
from .order_controller import OrderController
from .pdf import Pdf
class AddressLabel:
"""
A class for formatting data to be input into address label pdf.
...
Attributes
----------
order_controller : OrderController
member variable to access order instances
pdf : Pdf
member variable to invoke writing of pdf
Methods
-------
create_address_label(orders_selected):
Create strings to be output in pdf
"""
def __init__(self):
"""
Constructs all the necessary attributes for the AddressLabel object.
"""
self._order_controller = OrderController(None)
self._pdf = Pdf()
def create_address_label(self, orders_selected):
"""
For each of the orders selected with checkboxes will find the data for that order
and format is suitable for the pdf module.
Parameters:
orders_selected: an array of the row data from each row checked with a checkbox
(each item is a string).
"""
for index, order in enumerate(orders_selected):
order_id = int(order[0]) - 1
order_obj = self._order_controller.orders['order_' + order[0]]
address = [order_obj.customer.first_name + ' ' + order_obj.customer.last_name,
order_obj.customer.address.line_one, order_obj.customer.address.city]
self._pdf.write_address_label(address, order_id, index)
return address, order_id, index
This is what I have so far for test_address_label.py, but I notice that it is still contacting the main OrderController class and therefore failing - how can I stop this?
import pytest
from main.business_logic.address_label import AddressLabel
class Address:
def __init__(self, line_one, line_two, city):
self.line_one = line_one
self.line_two = line_two
self.city = city
class Customer:
def __init__(self, address, first_name, last_name):
self.address = address
self.first_name = first_name
self.last_name = last_name
class Order:
def __init__(self, customer):
self.customer = customer
class OrderController:
orders = {
'order_1': Order(customer=setup_customer())
}
def __init__(self, x):
pass
#staticmethod
def setup_customer():
def setup_address():
return Address(line_one='Test Line One',
line_two='Test Line Two', city='Test City')
address = setup_address()
return Customer(address=address, first_name='Test First Name', last_name='Test Last Name')
#pytest.fixture
def _order_controller():
return OrderController()
def test_address_label(_order_controller):
address_label = AddressLabel()
orders_selected = [['1', 'Test Name', '2021-03-12', 'Status', '£200']]
scenario_one_address = ['Test First Name Test Last Name', 'Test Line One', 'Test City']
address_label_contents = address_label.create_address_label(
orders_selected)
assert address_label_contents == (scenario_one_address, 1, 0)
In any case, if anyone had any good resources to learn this from that'd be great - I've read a lot of tutorials but they all use such elementary examples that don't apply to a lot of my use cases...
Thank you in advance!
Suppose I had this class
class employee(object)
def __init__(self,name):
return self.name
def something(self):
pass
...
Leading to
if __name__== "__main__":
name = input("what is your name ")
user1 = employee(name)
user1.something()
...
I want the user1 instance to be the name inputted by the user so that I can have unique instances. How do I go about adding instances based on user input in the main section?
so if I run the program and inputted "tim", the outcome I would want is:
tim.name = "tim"
....
UPDATE
Seems like the above is unclear, let me try to explain using my actual code:
So I have this Spotify API:
class Spotify(object):
def __init__(self,user):
self.client_id = ''
self.client_secret = ''
def client_credentials(self):
pass
def get_header_token(self):
pass
...
In the end,
if __name__== "__main__":
user = input("Enter username ")
user = Spotify(user)
user.request_author()
...
I am trying to get the user variable to the input the user provides, such as if the user inputted "tim123", the user variable would also be tim123.
So I could perform:
tim123.name
Think my mind is going completely blank and there should be an easy solution for this. I am sure this is very unpractical but I don't know how I would do this in case I ever needed to.
Change
return self.name
to
self.name = name
if name== "main":
variable_name = raw_input("Enter variable name:") # User.
enters "tim123"
name = input("Enter Name")
globals()[variable_name] = employee(name)
tim123.name
Based on your comment, it sounds like you are looking for exec() or eval(). Link. My solution would be to do something like:
class employee(object):
def __init__(self,name):
self.name = name
name = input("what is your name ")
exec(f"{name} = employee('{name}')")
(and then you would access joe.name, if the user inputted joe, or bob.name, if the user inputted bob, etc.).
Alternatively, you could use locals() or globals()
Hope this helped!
I seem to be making a stupid mistake that I cant find. Im simply trying to call my functions from my record class and having an invalid syntax error despite looking at sample code and trying to emulate the syntax.
Ive tried following tutorials and calling the function in every which way so the problem may not be in the calling of the function but something else I feel.
class definitions
class record:
def __init__(self,telephone,lastname,firstname):
self.telephone = telephone
self.lastname = lastname
self.firstname = firstname
def addrecord(self,x,y,z):
x = input('Enter telephone number')
y = input('Enter lastname')
z = input('Enter firstname')
phonebook.append(record(x,y,z))
return
def deleterecord(self,x):
phonebook[x-1].pop
return
Main
phonebook = record[]
addrecord(515,'fin','matt')
print(phonebook[0].firstname)
deleterecord(1)
print(phonebook[0].firstname)
If all this works I expect the output to be
"matt"
"null"
There are a number of problems with your code:
you are defining phonebook otuside of the class
in deleterecord you should call phonebook.pop(x).
there should be two classes that handle the phonebook and records, and the record could be modeled using a namedtuple.
there are syntax errors like calling record[] which is not valid Python.
Alternative implementation:
from collections import namedtuple
PhoneRecord = namedtuple("PhoneRecord", ['firstname', 'lastname', 'telephone'])
class PhoneBook:
def __init__(self):
self._phonebook = []
def addrecord(self, record):
self._phonebook.append(record)
return self._phonebook.index(record)
def deleterecord(self, i):
self._phonebook.pop(i)
phonebook = PhoneBook()
record_index = phonebook.addrecord(PhoneRecord(firstname="matt", lastname="snow", telephone="25512521"))
print(phonebook._phonebook)
phonebook.deleterecord(record_index)
print(phonebook._phonebook)
which will yield in the console:
[PhoneRecord(firstname='matt', lastname='snow', telephone='25512521')]
[]
The simplified version of your question is, given code
records = []
records.append("matt")
print(records[0])
del records[0]
print(records[0])
why don't I get the following output
"matt"
None
Instead, you get an IndexError exception.
The reason is that you are accessing an element beyond the size of the list, and Python handles this by raising an exception rather than returning None.
I am creating a class structure in python for a city, that stores the name, country, population and language for a city, all of which are input by the user. The information shall then be printed.
I think that I may be successful in storing the information within the class structure (although this may be wrong as well), but I am unsuccessful in printing the information. Currently, I am receiving the error that int object is not subscriptable.
class User():
def _init_(self, username, password, email, numOfLogins):
User.username = username
User.password = password
User.email = email
User.numOfLogins = numOfLogins
#User Record Array Creation
def createUserArray(num , User):
UserArray = []
for x in range(num):
UserArray.append(User)
return UserArray
#User Record Array Population
def populateUserArray(num, UserArray):
for x in range(len(userArray)):
UserArray[x].username = str(input("Enter username."))
UserArray[x].password = str(input("Enter password."))
UserArray[x].email = str(input("Enter email address."))
UserArray[x].numOfLogins = int(input("Enter number of logins."))
return UserArray
#User Record Array Display
def displayUserArray(UserArray, num):
for x in range(len(userArray)):
print(UserArray[x].username, UserArray[x].password, UserArray[x].email, str(UserArray[x].numOfLogins))
#Top Level Program
numOfUsers = 3
userArray = createUserArray(numOfUsers, User)
userArray = populateUserArray(numOfUsers, userArray)
displayUserArray(numOfUsers, userArray)
The contents of the class should all be displayed at the end of the program, but at the minute my program crashes due to the error - int object is not subscriptable.
you can always implement the method : __str__(self) of an object , and then when you just print it with :
your_obj = User(...)
print your_obj
your __str__(self) will be called and you can return from it whatever you want to print.
for example:
def __self__(self):
return `this class has the following attributes: %s %s %s %s` % (self.username,self.password,self.email ,self.numOfLogins )
and this what will get print, i think it is more efficient and well coded to work like that and not creating a function that print each class attribute separately.
The cause of your error is quite simple and obvious: you defined the function as displayUserArray(UserArray, num) but call it with displayUserArray(numOfUsers, userArray) - IOW you pass the arguments in the wrong order.
This being said, almost all your code is wrong, you obviously don't get the difference between a class and instance and how to use a class to create instances. I strongly suggest you read at least the official tutorial, and check a couple other tutorial and/or example code on the topic of classes and instances.
I'm Code doesn't seem to work, I am trying to get input of a job, category, and salary, and store the input
class Jobs:
def GetJob(self):
name = raw_input('Enter a Job Title: ')
category = raw_input('Enter what Category that Job is: ')
salary = raw_input('Enter the salary of that Job: ')
print name,category, salary
def __init__(self,name,category,salary):
self.name = Jobs.GetJob(name)
self.category = Jobs.GetJob(category)
self.salary = Jobs.GetJob(salary)
GetJob = Jobs()
print GetJob
Your code is totally out of good OOP practices, and the first part eandersson's answer too…
A class has for role to store values, get/set them and return (or apply) transformations to its encapsulated values. What you tried to achieve is totally nonsense: you're calling the GetJob method of the Jobs class inside another method. It could work if you would have written:
def __init__(self,name…):
self.name = Jobs.GetJob(self, name)
…
But that would be a wrong way to design your program. You'd better stick your class to hold your values and making it good at that, and make another function that helps populate your class:
class Jobs:
def __init__(self, name, category, salary):
self.name = name
self.category = category
self.salary = salary
def __repr__(self):
return "Jobs<%s,%s,%s>" % (self.name, self.category, self.salary)
def GetJob():
name = raw_input('Enter a Job Title: ')
category = raw_input('Enter what Category that Job is: ')
salary = raw_input('Enter the salary of that Job: ')
return Jobs(name, category, salary)
print GetJob()
I do not agree with eandersson's approach because it deceives the purpose of the constructor, by directly calling the GetJob method. Then GetJob is not useful. And one would want to be able to use the Job class without always having the raw inputs at construction. EDIT: valid only as a comment on the first part of his answer.
And finally, I think that you really misunderstands a lot about programming. You should better read thoroughly a python course like the ones on http://wiki.python.org/moin/BeginnersGuide/NonProgrammers, because there's really a lot of concepts you ignored to be able to write something like that.
go have a look at:
http://hetland.org/writing/instant-hacking.html
http://www.learnpython.org/
http://cscircles.cemc.uwaterloo.ca/
http://learnpythonthehardway.org/book/