Having trouble to understand how __str__ special method executes - python

I am not able to explain the behaviour of the following code when running it in PyCharm:
class Empty:
def __init__(self):
pass
def __str__(self):
print('in!')
return f'<{__name__}.Empty object at {hex(id(self))!r}>'
if __name__ == '__main__':
e = Empty()
The output:
in!
in!
There is no output when running the code from the terminal like this python .\my_script.py. May someone have an explanation for this? Thanks!

Related

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

Python 3.5 code - classes not correct defined

I have a simple code problem and do not know what I do wrong. The import part is OK, when I get as an error message is that, I guess I make a mistake with the classes.
status_listener = SessionStatusListener()
TypeError: interface takes exactly one argument
So the code is:
import clr
clr.AddReference ("fxcore2")
from fxcore2 import O2GTransport, IO2GSessionStatus
class SessionStatusListener(IO2GSessionStatus):
def __init__(self):
IO2GSessionStatus.__init__(self)
self.connected = False
def onLoginFailed(self, error):
print ("*** LOGIN FAILED: %s" % error)
def onSessionStatusChanged(self, status):
print ("NEW STATUS: %s" % status)
if status == O2GSessionStatusCode.Connected:
self.connected = True
The main Application starts here
if __name__ == "__main__":
session = O2GTransport.createSession()
status_listener = SessionStatusListener()
Any advice is appreciated.
Pass an argument to SessionStatusListener, like it's telling you to. I would imagine that you need to change the __init__ body to something like
super().__init__(self)
instead of
IO2GSessionStatus.__init__(self)
I believe it is saying that
status_listener = SessionStatusListener()
Needs one argument, like this:
status_listener = SessionStatusListener(1)
I'm not sure exactly what types of data it's expecting, but you need to pass in an argument.

setUp section in unit-tests seems to be ignored

class MyTests(unittest.TestCase):
def SetUp(self):
""" Setting up expected default values """
self.test = RandomTest()
def testReturnsArrayWithTuples(self):
result = self.test.next() # Error
self.assert_(len(result), 5)
if __name__ == "__main__":
unittest.main()
I have a basic test, but it fails with this error message:
AttributeError: 'MyTests' object has no attribute 'test'
Eclipse intellisense is showing me self.test though. What am I missing please?
Ok, its quite embarrassing, as it was just a typo. :)
def SetUp(self): has to be lowercase def setUp(self): in order to be found and executed.
I hope it prevents someone else chasing ghosts like I did.

Invoking a program in python

Is there a way for a program to invoke another program in python?
Let me explain my problem:
I am building an application (program 1) , I am also writing a debugger to catch exceptions (program 2) in program 1 { a typical try : except: } block of code . Now I want to release program 2 so that for any application like prog 1 , prog 2 can handle exceptions ( making my work easier) . I just want prog 1 to use a simple piece of code like:
import prog2
My confusion stems from the fact as how can I do something like this , how can I invoke prog 2 in prog 1, ie it should function as all the code in prog 1 should run in the {try: (prog 1) , except:} prog 2 try block.
Any pointers on how I can do this or a direction to start would we very much appreciated.
Note: I am using python 2.7 and IDLE as my developer tool.
tried execfile() yet? Read up on it on how to execute another script from your script.
I think you need to think about classes instead of scripts.
What about this?
class MyClass:
def __init__(self, t):
self.property = t
self.catchBugs()
def catchBugs(self):
message = self.property
try:
assert message == 'hello'
except AssertionError:
print "String doesn't match expected input"
a = MyClass('hell') # prints 'String doesn't match expected input'
UPDATE
I guess you have something like this in your directory:
program1.py (main program)
program2.py (debugger)
__init__.py
Program1
from program2 import BugCatcher
class MainClass:
def __init__(self, a):
self.property = a
obj = MainClass('hell')
bugs = BugCatcher(obj)
Program2
class BugCatcher(object):
def __init__(self, obj):
self.obj = obj
self.catchBugs()
def catchBugs(self):
obj = self.obj
try:
assert obj.property == 'hello'
except AssertionError:
print 'Error'
Here we are passing the whole object of your program1 to the BugCatcher object of program2. Then we access some property of that object to verify that it's what we expect.

declarations within python class equivalent to _init_?

I was wondering if the declarations put at the top of the python class are equivalent to statements in __init__? For example
import sys
class bla():
print 'not init'
def __init__(self):
print 'init'
def whatever(self):
print 'whatever'
def main():
b=bla()
b.whatever()
return 0
if __name__ == '__main__':
sys.exit( main() )
The output is:
not init
init
whatever
As a sidenote, right now I also get:
Fatal Python error: PyImport_GetModuleDict: no module dictionary!
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Any ideas on why this is? Thank you in advance!
No, it's not equivalent. The statement print 'not init' is run while the class bla is being defined, even before you instantiate an object of type bla.
>>> class bla():
... print 'not init'
... def __init__(self):
... print 'init'
not init
>>> b = bla()
init
They aren't exactly the same, because if you do c=bla() afterwards it will only print init
Also, if you reduce your main() to just return 0 it still prints the not init.
Declarations such as that are for the whole class. If print was a variable assignment rather a print statement then the variable would be a class variable. This means that rather than each object of the class having its own, there is only one of the variable for the whole class.
They are not equivalent. Your print statement outside the init method is only called once, when he class is defined. For example, if I were to modify your main() routine to be the following:
def main():
b=bla()
b.whatever()
c = bla()
c.whatever()
return 0
I get the following output:
not init
init
whatever
init
whatever
The not init print statement executes once, when the class is being defined.

Categories

Resources