Python main function in class - python

I'm new to python and the main() method and class def's are confusing me. I'm trying to create a bloom filter and my program keeps terminating because I don't think I'm calling things correctly.
class BloomFilter(object):
def __init__(self, numBits, numHashFunctions):
self.numBits = numBits
self.bitArray = [0] * numBits
self.hash = bloomFilterHash(numBits, numHashFunctions)
def insert(self, key):
def lookup(self, key):
def rand_inserts(self,num):
def main(): #not sure if i should put this inside or outside class
bloomfilter = BloomFilter(100,5)
bloomfilter.rand_inserts(15)
if __name__ == '__main__':
BloomFilter().main()
So if I wanted to create a bloom filter with 100 numBits and 5 hash functions, should i call that under the if __name__ == '__main__' or under def main()? I'm not sure if I'm calling these correctly as I'm much more familiar with Java. thanks!
def main():
bloomfilter = BloomFilter(100,5)
bloomfilter.rand_inserts(15)

the name == '__main__' clause is to make sure your code only runs when the module is called directly, not, for instance, if you are importing something from the module in another module. main() is not a special method for a python class, so I believe your objective here, in a simplified way, is the following:
class BloomFilter(object):
def __init__(self, numBits, numHashFunctions):
self.numBits = numBits
self.bitArray = [0] * numBits
self.hash = bloomFilterHash(numBits, numHashFunctions)
if __name__ == '__main__':
# creates an instance of the class
bloomfilter = BloomFilter(100,5)
# apply some method to instance...
bloomfilter.rand_inserts(15)

You would want to put main() outside the class:
class BloomFilter(object):
def __init__(self, numBits, numHashFunctions):
self.numBits = numBits
self.bitArray = [0] * numBits
self.hash = bloomFilterHash(numBits, numHashFunctions)
def insert(self, key):
def lookup(self, key):
def rand_inserts(self,num):
def main():
some_value = Bloomfilter(100, 5)
some_value.rand_inserts(15)
main()

Related

Method declared but not found in a class object

I just began the long and painful journey in Python Class Objects and try this:
class UgcObject:
def __init__(self, strPlateformeOld, strIdOld):
self.strPlateformeOld = strPlateformeOld
self.strIdOld = strIdOld
def GetApiUpdatedMetadata(self):
if self.strPlateforme == "youtube":
return True
def GetblnUpdatePossible(self):
return GetApiUpdatedMetadata()
if __name__ == '__main__':
ugc_test = UgcObject("youtube","id")
print(ugc_test.GetblnUpdatePossible())
I got an error message: NameError: name 'GetApiUpdatedMetadata' is not defined
I don't get why considering that I believe the GetApiUpdatedMetadata is declared and above the method that calls it.
What did I did wrong?
If you are trying to call another method in the same class it should have self. in front of it, and the variable name self.strPlateforme is wrong:
class UgcObject:
def __init__(self, strPlateformeOld, strIdOld):
self.strPlateformeOld = strPlateformeOld
self.strIdOld = strIdOld
def GetApiUpdatedMetadata(self):
if self.strPlateformeOld == "youtube":
return True
def GetblnUpdatePossible(self):
return self.GetApiUpdatedMetadata()
if __name__ == '__main__':
ugc_test = UgcObject("youtube","id")
print(ugc_test.GetblnUpdatePossible())

python, calling a method from another class

I am trying to call the sum_method function from my evaluation class to my main one, however I run into many errors. I want to use the new_data as the data parameter of my sum_method function.
evaluation class:
class evaluation():
def __init__(self, data):
self.data = data
def sum_method(self):
montant_init = self.data.loc[self.data['Initiateur'] == 'Glovoapp', 'Montant (centimes)'].sum()
print(montant_init)
main class:
class main(evaluation):
new_data.to_csv("transactions.csv", index=False)
self.data = new_data
def call_sum(self, new_data):
init_eval = evaluation.sum_method(self=new_data)
print(init_eval)
init_evalobj = main()
init_evalobj.call_sum()
if you use the method in your inherence class just use self
so:
init_eval = self.sum_method()
the self argument is passed in python automaticly as first parameter
update
you also should return a value:
def sum_method(self):
montant_init = self.data.loc[self.data['Initiateur'] == 'Glovoapp', 'Montant (centimes)'].sum()
print(montant_init)
return montant_init
I'd suggest making some changes to the both classes, to encapsulate the .data member variable in the base class. My preference would also be to separate out the calculation from the display, so leave all the print statements in the call_sum() function.
class evaluation:
def __init__(self, data):
self.data = data
def sum_method(self):
montant_init = self.data.loc[self.data['Initiateur'] == 'Glovoapp', 'Montant (centimes)'].sum()
return montant_init
class main(evaluation):
def __init__(self):
# Reduce csv content to what's needed for analysis
data_csv = pd.read_csv('transactions.csv')
# --> removing unnecessary data
new_data = data_csv[['Opération', 'Initiateur', 'Montant (centimes)', 'Monnaie',
'Date', 'RĂ©sultat', 'Compte marchand', 'Adresse IP Acheteur', 'Marque de carte']]
# --> saving changes...
new_data.to_csv("transactions.csv", index=False)
super().__init__(new_data) //Initialize the base class
def call_sum(self):
print('Glovoapp "montant" generated')
init_eval = self.sum_method() //Call the method from the base class
print(init_eval)

Python return value from class when an event happen

I have the main application in file main.py and some UI classes in uiwidgets.py.
in main.py I have:
import uiwidgets as uiw
uiw.MultiColumnListbox(header, data)
def doSomething(self, n)
do something with n
in uiwidgets.py I have:
class MultiColumnListbox(object):
def __init__(self, header, data):
self.header=header
self.data=data
...
self.tree.bind( "<Double-Button-1>", self.OnClick)
def OnClick(self, event):
global return_index
item = self.tree.identify('item',event.x,event.y)
if item is not "":
return_index = (int((item[1:4]),16) - 1)
n = self.data[return_index][0]
I need to return the n value from class to main.py when the user click the widget. How can I do?
You could just create a global variable in uiwidgets.py at the and and name it 'transfervar' or something like that. Then in main.py you import uiwidgets.py again. It should give you accses to 'transfervar' in main.py.
If the value of n is complicated or long, you can also write it into a textfile. But then you need the know-how how to write and read files. This is very nice to learn in "Think pythonger", by Allen B. Downey, chapter 14.
Your code with the global variable looks like this:
transfervar = None #just to create, you could set it 0, too
class MultiColumnListbox(object):
def __init__(self, header, data):
self.header=header
self.data=data
...
self.tree.bind( "<Double-Button-1>", self.OnClick)
def OnClick(self, event):
global return_index
item = self.tree.identify('item',event.x,event.y)
if item is not "":
return_index = (int((item[1:4]),16) - 1)
n = self.data[return_index][0]
global transfervar #needs to be declared as global
transfervar = n

How to check if a variable's value has changed

If I have a variable:
var = 5
I want to detect and jump to a function when the value of the variable changes, so if var is not equal to the value it was before, I want to jump to a function.
What is the easiest way to do this?
Another example:
from datetime import datetime
import time
def dereferentie():
currentMinute = datetime.now().minute
checkMinute(currentMinute)
def checkMinute(currentMinute):
#if currentMinute has changed do:
printSomething()
def printSomething():
print "Minute is updated"
def main():
while (1):
dereferentie()
if __name__ == '__main__':
main()
Building on #HelloWorld's answer and #drIed's comment: A nice way would be, to wrap this into a class.
For example:
class Watcher:
""" A simple class, set to watch its variable. """
def __init__(self, value):
self.variable = value
def set_value(self, new_value):
if self.variable != new_value:
self.pre_change()
self.variable = new_value
self.post_change()
def pre_change(self):
pass # do stuff before variable is about to be changed
def post_change(self):
pass # do stuff right after variable has changed
I would go with a setter function which triggers your needed function.
def setValue(val):
global globalVal
valueChanged= g_val != val
if valueChanged:
preFunction()
globalVal = val
if valueChanged:
postFunction()
A great way is to use the #property and #.setter decorators.
class MyClass:
#property
def property_name(self):
return self.some_value
#property_name.setter
def property_name(self, new_value):
self.some_value = new_value
obj = MyClass()
obj.property_name = "New Value"
stored_value = obj.property_name
By the way this is one of my favorite features in Python.
Original Poster
Here's how I would implement your example.
from datetime import datetime
class TimeManager:
# The actual variable holding data
# You don't need to declare it, but I like to
_current_minute = None
#property
def current_minute(self):
"""Retrieve the local variable value."""
return self._current_minute
#current_minute.setter
#current_minute.setter
def current_minute(self, value):
"""Same method name, but set the local variable."""
self._current_minute = value
print("Minute has updated to {}".format(self._current_minute))
#current_minute.deleter
def current_minute(self):
"""You can also delete variables."""
del self._current_minute
def main():
# Create the class
time_manager = TimeManager()
for i in range(100):
current_minute = datetime.now().second
# set the .currrent_minute using a #property
time_manager.current_minute = current_minute
if __name__ == '__main__':
main()

Returning values from callback(s) in Python

I am currently looking at trying to use a callback in Python.
What I would like to do is return a value from the callback and then use this return value for conditional processing. So for example if the user enters "Y" I would like to print something to the console.
As I am new to Python the code below is as close as I can get currently but:
a) I am not sure if it is the Pythonic way of doing it
b) the correct way of doing it?
class Observable:
def subscribe(self,callback):
self.callback = callback
def fire(self):
self.callback()
class CallBackStuff:
def doCallback(self):
userInput = raw_input("Please enter Y or N?")
return userInput
if __name__ == '__main__':
s = CallBackStuff()
o = Observable()
o.subscribe(s.doCallback)
t = o.fire()
print t
The easiest way I can think of to do this in your code is to just store the input as
a variable in the CallBackStuff object. Then after you've called the call-back function, you can just access the input data from the CallBackStuff instance. Example below.
class Observable:
def subscribe(self,callback):
self.callback = callback
def fire(self):
self.callback()
class CallBackStuff:
storedInput = None # Class member to store the input
def doCallback(self):
self.storedInput = raw_input("Please enter Y or N?")
if __name__ == '__main__':
s = CallBackStuff()
o = Observable()
o.subscribe(s.doCallback)
o.fire()
print s.storedInput # Print stored input from call-back object
class Observable(object):
def __call__(self, fun):
return fun()
class Callback(object):
def docallback(self):
inp = raw_input()
return inp
if __name__ == "__main__":
print Observable()(Callback().docallback)

Categories

Resources