How can I get this class to run in python? - python

class script(object):
def __init__(self, time_delay = 1.5):
self.time_delay = time_delay
self.lines = []
def run_script(self):
for line in self.lines:
print line
sleep(self.time_delay)
intro = script(1.5)
intro.lines = ["great", "boy"]

My guess would be that the sleep() function is from the time library. Just add
from time import *
at the beginning of the file. But, since the syntax above will import definitions as if they were declared in your file, you can use:
import time
...
time.sleep(self.time_delay)
But there is also another possibility. That sleep() has to be a function declared by you. If this is the case, you have to define it:
class script(object):
# ...
def sleep(delay):
# implementation
Note:
As #icktoofay commented, you are not using the run_script() method, so may want to add a call like:
intro.run_script()

There might be confusion on your part about "running" a class, since you don't "run" a class, but you can "run" a method of a class. Perhaps you just mean
intro.run_script()

Related

passing self with other argument on function call python

I have a little problem, I have my code below.
I want to call the "speak" function with two arguments inside the main() class.
When I call speak it says that self its not defined, and i don't know how to make it work...
Any ideas?
class main():
def blueon(self):
print("teste")
def speak(self,fala):
self.blueon
print(fala)
speak("testeaaaaa")
Try something like this.
Comments explain changes
class Main: # Class name capitalized and no parenthesis if the class has no base classs
def __init__(self): # class constructor. Initialize here your variables
pass
# if you have a function that doesn't use self, you can declare it static
#staticmethod
def blueon():
print("teste")
def speak(self, fala):
self.blueon() # added missing parenthesis
print(fala)
if __name__ == "__main__": # add this so you can later import your class as a library without executing your test code
m = Main() # instantiate the class
m.speak("testeaaaaa") # call the speak method
You run speak() in wrong way.
First you have to create instance of class m = main() and later use m.speak("text").
And you have to do with different indetation.
BTW: There is good rule to use CamelCaseName for classes - class Main(): - it helps to recognize class in code, and it allows to do main = Main().
More in PEP 8 -- Style Guide for Python Code
# --- classes ---
class Main():
def blueon(self):
print("teste")
def speak(self, fala):
self.blueon() # you forgot `()
print(fala)
# --- main ---
main = Main()
main.speak("testeaaaaa")

class declaration in exec inits class, but functions don't work

I am going to attach two blocks of code, the first is the main code that is ran the second is the testClass file containing a sample class for testing purposes. To understand what's going on it's probably easiest to run the code on your own. When I call sC.cls.print2() it says that the self parameter is unfulfilled. Normally when working with classes, self (in this case) would be sC.cls and you wouldn't have to pass it as a parameter. Any advice is greatly appreciated on why this is occuring, I think it's something to do with exec's scope but even if I run this function in exec it gives the same error and I can't figure out a way around it. If you'd like any more info please just ask!
import testClass
def main():
inst = testClass.myClass()
classInfo = str(type(inst)).split()[1].split("'")[1].split('.')
print(classInfo)
class StoreClass:
def __init__(self):
pass
exec('from {} import {}'.format(classInfo[0], classInfo[1]))
sC = StoreClass()
exec('sC.cls = {}'.format(classInfo[1]))
print(sC.cls)
sC.cls.print2()
if __name__ == '__main__':
main()
class myClass:
def printSomething(self):
print('hello')
def print2(self):
print('hi')

Self variable not updated after running function in different class

I have a class (AngleInfo) in a file (Display.py) with a self variable (WheelAngle) which is not updated after running a function (GetAngle). This function is being called in a class in a second file (ManageInfo.py) with a trigger based on events. When I try to use the WheelAngle in a second class (AngleProcess) in Display.py, the value doesn't update from the initialization. When the function is triggered in the MessageHandler class, it has access to raw data being represented by m in the GetAngle declaration.
There is another class (SpeedInfo) in a different file (Radar.py) where the self variable (VehicleSpeed) is being updated after running its corresponding information retrieval function (GetSpeed) in the ManageInfo class.
The working case has a threading system, but after replicating it in the non-working case I found no improvement. I don't understand why the WheelAngle is not being updated inside the class and comparing with the working case hasn't brought me closer to the answer.
So basically after I run GetAngle I see WheelAngle has the correct value inside that function but when I call the self variable in the UpdatePlot function of the AngleProcess class in the Display.py file I get the initial value. I even tried to create a different function in the AngleInfo class to access WheelAngle and then call this function in the UpdatePlot function in the AngleProcess class, but the result is the same.
Keep in mind a working example is not possible since it requires live data being sent. Also, even though WheelAngle and VehSpeed don't seem to be used, the code that follows has been ommited for simplicity!
Any ideas? There is a sample of the code below. Thank you!
Display.py
class AngleInfo():
def __init__(self):
self.WheelAngle = 0
def GetAngle(self,m):
self.WheelAngle = float(m) # Angle is correct
class AngleProcess():
def __init__(self):
self.AngleInfoObj = AngleInfo()
def UpdatePlot(self,tupledata):
WheelAngle = self.AngleInfoObj.WheelAngle # Angle is set to initial
Radar.py
class SpeedInfo(threading.Thread):
def __init__(self,page):
threading.Thread.__init__(self)
self.daemon = True
self.start()
self.VehSpeed = 0
def run(self):
VehSpeed = self.VehSpeed # Speed is correct
def GetSpeed(self,m):
self.VehSpeed = float(m) # Speed is correct
ManageInfo.py
from AurixCAN import Receiver
from Radar import SpeedInfo
from Display import AngleInfo
class MessageHandler:
def __init__(self,page):
self.SpeedInfo = SpeedInfo(page)
self.AngleInfo = AngleInfo()
DataSet = Receiver(canIDsandCalls={0xE:[self.SpeedInfo.GetSpeed,self.AngleInfo.GetAngle]})

Most pythonic way to declare inner functions

I'm writing an program where im using two main functions however those both functions uses same inner functions. I'm wondering how I should write them in most pythonic way? My point is to hide those helpers somewhere inside and to dont repeat helper functions.
def main_function1():
helper1()
helper2()
#dowork1
def main_function2()
helper1()
helper2()
#dowork2
def helper1()
#workhelp1
def helper2()
#workhelp2
The only reasonable solution which i can figure out is declaring static class with.. private functions? But since:
Strictly speaking, private methods are accessible outside their class,
just not easily accessible. Nothing in Python is truly private[...]
Im stuck and out of ideas.
From: http://www.faqs.org/docs/diveintopython/fileinfo_private.html
Topic: Why are Python's 'private' methods not actually private?
Also I thought about declaring one main function with inner helpers and with switcher as a argument to determine which function should run but I guess thats pretty poor solution.
For now only way I find the most accurate is to declare normal class as:
class Functions:
def main_function1(self):
print("#first function#")
self.helper1()
self.helper2()
def main_function2(self):
print("#second function#")
self.helper1()
self.helper2()
def helper1(self):
print("first helper")
def helper2(self):
print("second helper")
Functions().main_function1()
Functions().main_function2()
print("###")
Functions().helper1()
Output:
#first function#
first helper
second helper
#second function#
first helper
second helper
###
first helper
But also here i can access helpers which isnt a big deal but still gives me a reason to wonder.
There are no private functions in Python. Rather, by prefixing the names of methods intended to be non-public with underscores, you signal to users of your class that those methods are not meant to be called externally:
class Functions:
def main_function1(self):
print("#first function#")
self._helper1()
self._helper2()
def main_function2(self):
print("#second function#")
self._helper1()
self._helper2()
def _helper1(self):
print("first helper")
def _helper2(self):
print("second helper")
This is in line with the principle of "We're all consenting adults here" - you can touch the non-public methods of a class, but if you use them wrongly, that's on your own head.
Try this
def get_main(name):
def helper1():
print("helper1")
def helper2():
print("helper2")
def main1():
print("Running helpers from main1")
helper1()
helper2()
def main2():
print("Running helpers from main2")
helper1()
helper2()
if name == "main1":
return main1
if name == "main2":
return main2
main1 = get_main("main1")
main2 = get_main("main2")
You can then run the function as follows:
main1()
main2()
helper1()
output:
Running helpers from main1
helper1
helper2
Running helpers from main2
helper1
helper2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'helper1' is not defined

Create functions within classes in google app engine?

I was trying to include my own functions in mainpage class, but when calling them it's not working at all, so what i did is to create a class for it and included that function in it. and in get () of mainpage class i created an instance for that class and called the function like object_name.function name() but it ain't working
class encipher:
def time_stomp():
t1=time.time()
dt = datetime.now()
dt.now()
stri=""
stri+=(str(dt.minute*dt.microsecond)[0:4])
stri+=(str(dt.second*dt.microsecond)[0:2])
stri+=(str(dt.microsecond)[0:3])
stri+=(str(dt.microsecond)[2:3])
stri+=(str(dt.microsecond)[1:2])
stri+=(str(dt.microsecond)[0:1])
return stri
#-------------------------------------------------------------
def keygen():
key_stri=""
ko=0
datalist_str1=self.time_stomp()
for i in range(6):
key_stri+=((hex(operator.xor(int(datalist_str1[ko:ko+2]),128)).replace("0x","")).zfill(2))
ko+=2
#print "Key:",key_stri
#print "Key:",key_stri
#print "Key:",key_stri
return key_stri
class MainPage(webapp.RequestHandler):
def get(self):
ddes=encipher()
global final_data_hex
global username
global filename
username = self.request.get("name")
filename=self.request.get("filename")
addr=self.request.get("mac")
path="d:/xampp/htdocs/encrypt/"+username+'/'+filename
f1 = open(path, 'r')
#f1=open(path,"r")
string=f1.read()
i=0
addr=addr.replace(":",'')
#self.response.out.write(ddes.keygen())
A python instance method needs to accept at least one parameter, self. "It's not working" is a horrible explanation of a problem; if you'd read your tracebacks you'd see an error about .keygen() accepting 0 arguments with 1 provided.
But yes, there's no reason to encapsulate methods in a class if what you really want is a function.
I figured it out. We can simply include functions out of the class and it will work perfectly.

Categories

Resources