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())
Related
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()
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.
class Network():
tables = []
def readInFile():
network = Network()
def printThing(network):
print(len(network.tables))
def main():
network = readInFile()
printThing(network)
if __name__ == "__main__":
main()
gives error:
File "thing.py", line 6, in printThing
print(len(network.tables))
AttributeError: 'NoneType' object has no attribute 'tables'
But the object network isn't NoneType it's clearly of type Network() when it is instantiated in the readInFile function, and type Network() has the attribute tables! Please help, thanks
You need to return something from your function. Unless your function has a return statement in it, it will return None
class Network():
tables = []
def readInFile():
return Network()
def printThing(network):
print(len(network.tables))
def main():
network = readInFile()
printThing(network)
if __name__ == "__main__":
main()
Your function readInFile() does not have a return statement and therefore always returns None.
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)
I'm writing an interpreter in Python for a very simple language grammar. I have a superclass called Statement which has several child classes. I have a method in the superclass called CreateStatement that evaluates keywords, and based on the keyword found it creates an instance of a child class object. Some of the child classes will need to call this method.
My problem is that I'm getting this error:
AttributeError: 'Statement' object has no attribute 'Assignment'
Help!
import re
from TokenHandler import TokenHandler
from ParserException import ParserException
class Statement(object):
tokens = []
executedTokens = []
def __init__(self, tokenlist):
self.tokens = tokenlist
def getCurrentToken(self):
print self.tokens[0]
return self.tokens[0]
def createStatement(self):
currenttoken = self.getCurrentToken()
t = TokenHandler()
if currenttoken == "print":
p = Print(self.tokens)
return p
elif t.isVariable(currenttoken):
a = Assignment(self.tokens)
return a
elif currenttoken == "if":
i = IF(self.tokens)
return i
elif currenttoken == "while":
w = While(self.tokens)
return w
elif currenttoken == "begin":
s = self.CompoundStatement(self.tokens)
return s
else:
raise ParserException('Reserved word \'end\' expected')
#...other methods...
from Statement import Statement
from TokenHandler import TokenHandler
import VariableException
class Assignment(Statement):
def __init__(self, tokens = []):
super(Assignment, self).__init__(tokens)
#...other methods...
a = self.Assignment(self.tokens)
is wrong if Assignment is a subclass defined at the module level and not an attribute of the Statement class or the self instance. Did you mean
a = Assignment(self.tokens)
This line is probably similarly wrong:
s = self.CompoundStatement(self.tokens)