python program without stackless.run() - python

How the below program execute my member A.fun without calling stackless.run() in the program?
import stackless
class A:
def __init__(self,name):
self.name = name
self.ch = stackless.channel()
stackless.tasklet(self.fun)()
def __call__(self,val):
self.ch.send(val)
def fun(self):
while 1:
v = self.ch.receive()
print "hi" , v
if __name__ == "__main__":
obj = A("sh")
obj(6)
output:
hi 6

I've never used stackless, but I'm guessing from the documentation that calling channel.send makes the scheduler call the other tasklet.

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())

Calling methods from other files in python results in executing the entire python file [duplicate]

This question already has answers here:
Why is Python running my module when I import it, and how do I stop it?
(12 answers)
Closed 3 years ago.
I am new to python programming. I have written sample code as flows.
temp.py
p = 'Tushar'
print(p)
class Basics:
def __init__(self, name, phNum):
self.name = name
self.phNum = phNum
def getString(self):
temp = self.name+' '+str(self.phNum)
print(type(temp))
return temp
bs = Basics("tushar", 9620207652)
x = bs.getString()
print(x)
def isBlue(isBlue):
if(isBlue):
print('Boolean true')
x = 'true'
else:
print('Boolean false')
x = 'false'
return x
tus = isBlue(True)
if(tus != None):
str = bs.getString().split(' ',1)
print(str[0])
print(str[1])
Hello.py
from temp import Basics
class Check:
def __init__(self):
print('Check obj')
def createName(self, firstName, lastName):
str = firstName + ' ' + lastName
return str
emp = Check()
completeName = emp.createName('Tushar', 'Banne')
print(completeName)
b = Basics('Tushar', 98765432)
val = b.getString
print("Val is {}".format(val))
I am running Hello.py file and getting the below output.
Tushar
class 'str'
tushar 9620207652
Boolean true
class 'str'
tushar 9620207652
Check obj
Tushar Banne
Val is (bound method Basics.getString of 0x0000024ECCCB5B70
The questions that I have are as follows
Why is the entire temp.py getting executed?
How to execute only getString method.
Why is it that when I use parenthesis after getString, it fails.
Why is the val printing object reference?
Am I following the correct standards of python coding?
Why is the entire temp.py getting executed?
That's how it works. Importing a module means essentially executing it.
How to execute only getString method.
In order to do so, the code in temp.py has to be changed in a way that it is only executed when the module is run at highest level ("as the __main__ module") instead of imported.
You do that this way:
if __name__ == '__main__':
p = 'Tushar'
print(p)
class Basics:
def __init__(self, name, phNum):
self.name = name
self.phNum = phNum
def getString(self):
temp = self.name+' '+str(self.phNum)
print(type(temp))
return temp
if __name__ == '__main__':
bs = Basics("tushar", 9620207652)
x = bs.getString()
print(x)
def isBlue(isBlue):
if(isBlue):
print('Boolean true')
x = 'true'
else:
print('Boolean false')
x = 'false'
return x
if __name__ == '__main__':
tus = isBlue(True)
if(tus != None):
str = bs.getString().split(' ',1)
print(str[0])
print(str[1])
Why is it that when I use parenthesis after getString, it fails.
I don't see it fail in your question.
Why is the val printing object reference?
Because you asked it to. Referring to a method or function means seeing it as an object and printing its string representation. If you call it (with the () behind), you perform a function call.
First, check this out What does if __name__ == "__main__": do?
When you are importing a python file, all of the code is executed.
What do you mean fails, what is the error?
val = b.getString means that now val references the method getString, that's why it is printed.
No, read the link above, also, python uses snake_case, not camelCase, so call the method get_string, not getString. (this obviously doesn't changes thte

Python main function in class

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()

Access "a method of a class" in "a function of another python file" by passing the class as that function's parameter

I have a class file. Let's call it "C1.py". The sample code looks like below.
class C1(object):
def __init__(self):
self.greeting = "Hello, world!"
def M1(ans):
if ans == 1 or ans == 2:
return True
else:
return False
Now, I have another python file in the same folder, which will access the class file shown above.
from trial import C1
def getAns(class1):
while True:
ans = input("Answer: ")
if class1.M1(ans):
return ans
break
sample = C1()
print sample.greeting
ans = getAns(sample)
print ans
When I run those files, sample.greeting prints fine. Everything is fine until when the execution reaches the line "ans = getAns(C1)", which gives the error "M1() takes exactly 1 argument (2 given)".
So, where in the code should I change so that I can call that method successfully?
Note here that the above code is only the abstraction of my whole program to highlight my problem. It sounds stupid with just the code above alone. So, please, please bear with that for me.
M1 is currently defined as a method of C1, as such it needs to have an additional self argument which would be the instance of the class. I.e
class C1(object):
def __init__(self):
self.greeting = "Hello, world!"
def M1(self, ans):
if ans == 1 or ans == 2:
return True
else:
return False
In other languages such as C++ or Java the presence of self (or this) is implicit, but in python it's explicit.
alternatively if you don't want or need M1 to access C1's state you could make M1 static via #staticmethod i.e.
class C1(object):
def __init__(self):
self.greeting = "Hello, world!"
#staticmethod
def M1(ans):
if ans == 1 or ans == 2:
return True
else:
return False

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