Python,unable to call initial arguments outside the class - python

The below python class have empty dictionary as initial arguments, after calling
createAccount() outside class it successfully add data to dictionary but I can't access dictionary outside class.
What changes shall I make in the below code to access the newly created account details ?
*Please note that my error occurs in the last line of the code *
class SavingsAccount():
def __init__(self):
self.savingsAccounts = {}
def createAccount(self, name, initialDeposit):
print()
self.accountNumber = int(12345)
self.savingsAccounts[self.accountNumber] = [name, initialDeposit]
print("Account creation has been successful. Your account number is ", self.accountNumber)
SavingsAccount().createAccount(name = 'a',initialDeposit=4)
print(SavingsAccount().savingsAccounts[12345]) # getting error here

You should initialize your object using __init__,
class SavingsAccount:
def __init__(self, name, initial_deposit):
self.accountNumber = 12345
self.savingsAccounts = {self.accountNumber : [name, initial_deposit] }
print("Account creation has been successful. Your account number is ", self.accountNumber)
saving_account = SavingsAccount(name='a', initial_deposit=4)
print(saving_account.savingsAccounts)
Also, most of the Pythonistas prefer snake_casing while naming variables.

You are creating a new instance of SavingsAccount with every call. After you call to createAccount completes, that instance is garbage-collected, as there are no references to it stored anywhere.
s = SavingsAccount()
s.createAccount(name='a', initialDeposit=4)
print(s.savingsAccounts[12345])
(See Taohidul Islam's answer for how you should be defining the class, though.)

The line that gives the error does this actions:
Calls SavingsAccount.init() to create the object
Asks for the item 12345 in the dictionary (that whas just created so it's empty)
You should structure your code in a different way. You should have a list of accounts or similar that is unique, and then insert in it the accounts you create.

Must first initialize an instance of your SavingsAccount class
#initialize savings account object
s = SavingsAccount()
#call created account method
s.createAccount(name="a", initialDeposit=4)
#print the account
print(s.savingsAccounts[12345])
Although your datastructure is confusing, why not have one instance of a savings account object represent an individuals account? Then you could just assign member variables for values you want to track.
class SavingsAccount:
def __init__(self, name, initial_deposit):
self.account_name = name
self.bal = initial_deposit
def deposit(self, val):
self.bal += val
def return_account(self):
return self.__dict__
Now you can use it more simplistically
s = SavingsAccount("name", 500)
s.deposit(500)
acc = s.return_account()
print(acc)
>> {"account_name": "name", "bal": 1000}

Related

How can I use a function to create a persistant list correlated to the given arguments?

I'm writing a script to find the moving average of different stocks. This script runs continuously, looping through my API call to add the current price to a list before averaging it. This works fine, however I'd like to be able to put this into a function to where the only input I need to give it is the name of the stock. I'd like this script to work for as many stocks as I want to specify, at the same time. That's where I run into issues because for each stock I have I need to have an empty list predefined that can hold the pricing information.
I've been trying to use the name of the stock to then create a related list, but as I now understand it it's not a great idea using one variable name to create another variable, so I'm not sure what to do. I believe the usual solution here would be to use a dictionary, but I'm a beginner to programming in general so I haven't figured out how to fit that into my situation. Any help would be greatly appreciated.
def sma(stock_name):
list_exists = stock_name + "_list" in locals() or stock_name + "_list" in globals()
if list_exists:
print()
else:
stock_name + "_list" = [] # Problem line, I would like for this to create a list called stock_name_list
stock_price = requests.get("myapi.com", params={"stock_name": stock_name, "bla bla": "blah"})
stock_name_list.append(stock_price)
When you have an operation based on a version of the data specific to that operation, that is usually a good time to think about using classes. This particular proposed class will encapsulate the name of a stock, the list of data specific to it, and perform sma on it:
class Stock:
n = 10
def __init__(self, name):
self.name = name
self.data = []
def sma(self):
stock_price = requests.get("myapi.com", params={"stock_name": self.stock_name, "bla bla": "blah"})
self.data.append(stock_price)
window = self.data[-n:]
return sum(window) / len(window)
Now you can maintain a dictionary of these objects. Any time you encounter a new stock, you just add an item to the dictionary:
stocks = {}
def sma(name):
stock = stocks.get(name)
if name is None: # None is what get returns when the key is missing
stock = Stock(name)
stocks[name] = stock
return stock.sma()
The nice thing is that you now have a dictionary of named datasets. If you want to add a different statistic, just add a method to the Stock class that implements it.
I defined a global sma function here that calls the eponymous method on the object it finds in your dictionary. You can carry encapsulation to an exterme by making the method perform the action of the function if called statically with a name instead of an instance. For example:
class Stock:
n = 10
named_stocks = {} # This is a class variable that replaces the global stocks
def __init__(self, name):
self.name = name
self.data = []
def sma(self):
if isinstance(self, str):
self = Stock.get_stock(self)
stock_price = requests.get("myapi.com", params={"stock_name": self.stock_name, "bla bla": "blah"})
self.data.append(stock_price)
window = self.data[-n:]
return sum(window) / len(window)
#classmethod
def get_stock(cls, name):
stock = cls.named_stocks.get(name)
if stock is None:
stock = cls(name)
cls.named_stocks[name] = stock
return stock
Now that there is a check for isinstance(self, str), you can call the sma method in one of two ways. You can all it directly on an instance, which knows its own name:
aapl = Stock('AAPL')
aapl.sma()
OR
Stock.get_stock('AAPL').sma()
Alternatively, you can call it on the class, and pass in a name:
Stock.sma('AAPL')
use defaultdict
from collections import defaultdict
stock_name_to_stock_prices = defaultdict(list)
stock_name_to_stock_prices['STOCK_NAME'].append(123.45)

How do I select a row in sqlite with a name on the row instead of an id with python?

I'm programming a store management system in python using sqlite as database. I want to be able to see Item price when the name of the item is entered instead of the Item id...below is the code snippet
def ajax2(self, *args, **kwargs):
self.get_name = self.entername_e.get()
#get the products info with that name or id and fill labels above
query = "SELECT * FROM inventory WHERE name=?"
result = c.execute(query, (self.get_name, ))
for self.r in result:
self.get_name = self.r[1] #name
self.get_price = self.r[4] #sp
self.get_stock = self.r[2] #stock
self.productname.configure(text="Product's Name: "+ str(self.get_name))
self.pprice.configure(text="Price: Gh "+str(self.get_price))
Anytime I run the code after entering the name in the label Entry, the name appears even if it's not in the database and an error message follows in the command line like below:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\GH\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in
__call__
return self.func(*args)
File "main.py", line 96, in ajax2
self.pprice.configure(text="Price: Gh "+str(self.get_price))
AttributeError: 'Application' object has no attribute 'get_price'
PS C:\Users\GH\Desktop\Developments\Store Management Software>
If the name is not present in the database, the cursor returned by the query is empty and the loop is not entered. As a result, self.get_name is unchanged and keeps the entered value, and self.get_price is not set, hence the error.
You shoud explicitely test for that case:
...
result = c.execute(query, (self.get_name, ))
empty = True
for self.r in result:
empty = False
self.get_name = self.r[1] #name
self.get_price = self.r[4] #sp
self.get_stock = self.r[2] #stock
if empty: // name is not present in database
...
I don't think that you understand the object oriented approach in this python code. The self keyword is used to access the underlying object, of which all the attributes should be defined in the init function of the class. These attributes should only be there to represent the state of an instantation of the class. See this link : link
You should always be careful when altering objects by accessing the attributes directly. A common practice is to only access them by getters and setters, e.g.
def getAttribute_1(self):
return self.attribute_1
There are lots of good books and tutorials about object oriented programming available if you want to learn more about it, just google it.
In this case, for example, I don't see why you do:
for self.r in result: ...
when you should let go off the self keyword:
for r in result: ...
As this result variable is only relevant within the scope of your function.
Furthermore, if you want to set the price attribute of your current object, you should define that attribute in the init function:
def __init__(self, ...)
self.price = 0 """or whatever default value
you want to give it, or initiate it by giving the initial
value as an argument for the constructor"""
maybe define a getter and setter like this:
def get_price(self):
return self.price
def set_price(self, new_price):
self.price = new_price
Then use these methods in your ajax function. Just remember to make a distinction between local variables, e.g. price = result[4] which are only relevant in this function, and attributes of your object, like self.price! These are 2 very different concepts.
To respond to your error in this example: the get_price is not set if the results returned by the query are None, in which case the loop will not be entered. In this case, the self.get_price attribute of you object has never been created, hence the error.
Hope this helps

Method __init__ has too many parameters

I'm super new to Python (I started about 3 weeks ago) and I'm trying to make a script that scrapes web pages for information. After it's retrieved the information it runs through a function to format it and then passes it to a class that takes 17 variables as parameters. The class uses this information to calculate some other variables and currently has a method to construct a dictionary. The code works as intended but a plugin I'm using with Pycharm called SonarLint highlights that 17 variables is too many to use as parameters?
I've had a look for alternate ways to pass the information to the class, such as in a tuple or a list but couldn't find much information that seemed relevant. What's the best practice for passing many variables to a class as parameters? Or shouldn't I be using a class for this kind of thing at all?
I've reduced the amount of variables and code for legibility but here is the class;
Class GenericEvent:
def __init__(self, type, date_scraped, date_of_event, time, link,
blurb):
countdown_delta = date_of_event - date_scraped
countdown = countdown_delta.days
if countdown < 0:
has_passed = True
else:
has_passed = False
self.type = type
self.date_scraped = date_scraped
self.date_of_event = date_of_event
self.time = time
self.link = link
self.countdown = countdown
self.has_passed = has_passed
self.blurb = blurb
def get_dictionary(self):
event_dict = {}
event_dict['type'] = self.type
event_dict['scraped'] = self.date_scraped
event_dict['date'] = self.date_of_event
event_dict['time'] = self.time
event_dict['url'] = self.link
event_dict['countdown'] = self.countdown
event_dict['blurb'] = self.blurb
event_dict['has_passed'] = self.has_passed
return event_dict
I've been passing the variables as key:value pairs to the class after I've cleaned up the data the following way:
event_info = GenericEvent(type="Lunar"
date_scraped=30/01/19
date_of_event=28/07/19
time=12:00
link="www.someurl.com"
blurb="Some string.")
and retrieving a dictionary by calling:
event_info.get_dictionary()
I intend to add other methods to the class to be able to perform other operations too (not just to create 1 dictionary) but would like to resolve this before I extend the functionality of the class.
Any help or links would be much appreciated!
One option is a named tuple:
from typing import Any, NamedTuple
class GenericEvent(NamedTuple):
type: Any
date_scraped: Any
date_of_event: Any
time: Any
link: str
countdown: Any
blurb: str
#property
def countdown(self):
countdown_delta = date_of_event - date_scraped
return countdown_delta.days
#property
def has_passed(self):
return self.countdown < 0
def get_dictionary(self):
return {
**self._asdict(),
'countdown': self.countdown,
'has_passed': self.has_passed,
}
(Replace the Anys with the fields’ actual types, e.g. datetime.datetime.)
Or, if you want it to be mutable, a data class.
I don't think there's anything wrong with what you're doing. You could, however, take your parameters in as a single dict object, and then deal with them by iterating over the dict or doing something explicitly with each one. Seems like that would, in your case, make your code messier.
Since all of your parameters to your constructor are named parameters, you could just do this:
def __init__(self, **params):
This would give you a dict named params that you could then process. The keys would be your parameter names, and the values the parameter values.
If you aligned your param names with what you want the keys to be in your get_dictionary method's return value, saving off this parameter as a whole could make that method trivial to write.
Here's an abbreviated version of your code (with a few syntax errors fixed) that illustrates this idea:
from pprint import pprint
class GenericEvent:
def __init__(self, **params):
pprint(params)
event_info = GenericEvent(type="Lunar",
date_scraped="30/01/19",
date_of_event="28/07/19",
time="12:00",
link="www.someurl.com",
blurb="Some string.")
Result:
{'blurb': 'Some string.',
'date_of_event': '28/07/19',
'date_scraped': '30/01/19',
'link': 'www.someurl.com',
'time': '12:00',
'type': 'Lunar'}

Class Variable NameError not defined python

In this example, it's working
hotels as a class variable no NameError
class Hotel():
"""""""""
this is hotel class file
"""
hotels = []
def __init__(self,number,hotel_name,city,total_number,empty_rooms):
self.number = number
self.hotel_name = hotel_name
self.city = city
self.total_number = total_number
self.empty_rooms = empty_rooms
Hotel.hotels.append([number,hotel_name,city,total_number,empty_rooms])
def list_hotels_in_city(self,city):
for i in hotels:
if city in i:
print "In ",city,": ",i[1],"hotel, available rooms :",i[4]
In the following example its not working
from twilio.rest import Client
class Notifications():
customers = []
def __init__(self,customer_name,number,message):
self.customer_name = customer_name
self.number = number
self.message = message
Notifications.customers.append([customer_name,number,message])
def send_text_message(self,customer_name):
for i in customers:
print "triggeredb"
inst = Notifications("ahmed","+00000000000","messagesample")
print "instance : ",inst.customers
inst.send_text_message("ahmed")
NameError: global name 'customers' is not defined
Update
for first example nothing called to show error
but issue solved for second example Thanks Tom Dalton , scharette and James
As I said in my comment, When you call for i in customers:, customers is not in scope of that function.
I just wanted to add also, that you use
Notifications.customers.append([customer_name,number,message])
but you also declare
customers = []
Note that the former is a class variable and will share the variable among Notifications instances. The latter represent an instance variable. If your goal is to have a customers list for every specific object, you should use self.customers.
So basically,
You want shared list between objects ?
for i in Notifications.customers:
You want specific list for every object ?
for i in self.customers:
I think it's very likely that when you ran your first example, you had a variable called hotels in your global (interpreter) scope. Thats why it's working. If I copy paste your example into my interpreter it fails with the same error message as your second code sample.
If your send_text_message function only accesses class variables (no instance variables) I would recommend making it a class method like this :
#classmethod
def send_text_message(cls, customer_name):
for i in cls.customers:
print "triggeredb"
That way you can access the class variables using the cls variable and won't have to repeat the class name in your function (which is nice, as if you change the class name - you won't have to go hunting through your code for repetitions).

Accessing elements of lists, and calling their fuctions

Here is Customer class:
class Customer:
def __init__(self, timestamp, cid, item_count):
self.time_stamp = timestamp
self.customer_name = cid
self.item_count = item_count
def checkout(self, new_timestamp):
self.time_stamp = new_timestamp
def get_cus_name(self):
return self.customer_name
If I create an empty list of Customer objects like:
customers = [Customer]
And then somewhere else I try to call Customer methods in a loop like:
def checkout_customer(self, cid):
for cus in self.customers:
if cus.get_cus_name == cid:
cus.checkout(self.cur_num_customers + 7)
why do I get an error when I try to call cus.checkout? My ide tells me that it expects a Customer but got an int. Why doesn't it pass itself into the 'self' arg here?
However if I just create a Customer object and directly call its methods, it works fine:
def foo(self):
cus = Customer(1,'pop',2)
cus.checkout(23)
This is my first time learning python, and ive been stuck trying to figure out lists, and accessing its members. Perhaps my initialization of self.custormers = [Customer] is incorrect?
EDIT:
In my constructor of tester class I create an empty list like this:
self.customer = [Customer]
I am able to add customers no problem:
def add_custormer(self, customer):
self.customers.append(customer)
My problem is not adding customers, but accessing their methods once they are in a list. Doing something like this self.customers[0].checkout(1,'pop',2) gives me an error "Expected type 'Customer' got int".
I am not sure of the class where checkout_customer lives but I am assuming you declare the list self.customers somewhere in it.
self.costumers = []
If you intend to add an element Customer to the list you should use something like: self.customers.append(Customer(x,y,z)) since you want to add a new customer to the list and when doing so you are required to initialize the Customer class.
I didn't try the code but I believe something like this should work:
def foo(self):
self.customers.append(Customer(1,'pop',2))
self.checkout_customers(23)

Categories