What does this empty threading class do? - python

In this example, there's a threading subclass defined that I don't think does anything.
class ThreadClass(threading.Thread):
def run(self):
return
class otherClass(baseClass):
def __init__(self, foo):
bar
def main():
t = threadClass()
t.start()
oc = otherClass()
What does ThreadClass do?

If you go to the doc: https://docs.python.org/2/library/threading.html and look at the 16.2.1. Thread Objects section, I am pretty sure you will find the answer.
ThreadClass shows you the basic usage of writing your own class by deriving it from threading.Thread. It would make more sense if you try to do something in the run()
By writing your own class by deriving it from threading.Thread, you can have more flexibility for your own multi-thread tasks.

Related

How to call class function from seperate class function through Threading module Python

I'm coding my own Asteroids minigame using pygame (which is extremely inefficient with multiple sprites so wanted to use threading.
How do I access a function from another class (asteroids class) through my main class (handler) class.
If my class system is backwards or doesn't work using Threading, please explain to me how I could make it more efficient or easy to code in
class Asteroids():
def __init__(self):
....
def Update(self):
....
class Handler():
def __init__(self):
....
def Update_All(self):
x = threading.Thread(target = ##Asteroids.Update()
x.start()
thanks in advance
You need to create an instance of Asteroids
astroid = Astroids()
# then you can use the function in your thread
x = threading.Thread(target = astroid.Update)

python overriding method without re-copying whole code

I have a class Father whom I call run method to do the work. I inherit this class with a Child class. This look like this:
class Father:
def __init__(self):
...
def run(self):
work1()
work2()
....
class Child(Father):
def run(self):
pass
Usually, I use pass, as most of the time, children do same things as father, just being called from distinct contexts. However, sometimes the behavior changes. But when it does, work1, work2, and so on from Father are still being executed. Only a last workn should be added.
How is it possible to override run method without having to copy the whole code from Father.run, and just adding a last work instruction? I have tried this, which is working:
class Father:
def run(self):
work1()
...
run_additionnal_stuf()
def run_additionnal_stuf(self):
pass
class Child(Father):
def run_additionnal_stuf(self):
work()
However, is there any solution more elegant?
First of all, if your Child class doesn't change a method you don't need to define it with pass. Simply do nothing and thanks to inheritance magic, the child instance will also have that method.
As to your actual question, if you only want to add functionality to a child instance, you can use super. Indeed, from the docs:
This is useful for accessing inherited methods that have been
overridden in a class.
So you could do:
class Child(Father):
def run(self):
super().run()
work_n()
A simple demonstration:
class Father:
def run(self):
print("In Father")
class Child(Father):
def run(self):
super().run()
print("In Child")
f = Father()
c = Child()
f.run()
c.run()
And this expectedly prints out:
In Father
In Father
In Child

Python object composition - accessing a method from the class that called it

You'll have to forgive me, I am trying to teach myself OO but I have come across this problem with composition and 'has-a' relationships.
class Main(object):
def A(self):
print 'Hello'
def B(self):
self.feature = DoSomething()
class DoSomething(object):
def ModifyMain(self):
#Not sure what goes here... something like
Main.A()
def run():
M = Main()
M.B()
A real world example of the above simplification is a PySide application where Main is a MainWindow, and DoSomething is a dynamically created widget that is placed somewhere in the window. I would like DoSomething to be able to modify the status bar of the mainwindow, which is essentially calling (in Main) self.statusbar().
If there is a shortcut in PySide to do this, Tops!! please let me know! However, I'm actually after the more general Pythonic way to do this.
I think I'm close ... I just can't make it work...
Why don't you use a signal and slot instead? That's a more Qt and OOP way of doing this.
In your dynamically created widget class:
self.modifyMain = QtCore.Signal(str)
In your main class:
#QtCore.Slot(str)
def changeStatusbar(self, newmessage):
statusBar().showMessage(newmessage)
in you main class after creating your widget:
doSomething.modifyMain.connect(self.changeStatusbar)
And in you widget class, where you want to change the statusbar of main, you say:
modifyMain.emit("Hello")
None of this is tested as I don't have a PySide installation handy.
There are two problems with your code:
At no time do you call ModifyMain; and
Main.A() will result in an error, because A is an instance method, but you are calling it on a class.
You want something like:
class Main(object):
def A(self):
print 'Hello'
def B(self):
self.feature = DoSomething() # self.feature is an instance of DoSomething
self.feature.ModifyMain(self) # pass self to a method
class DoSomething(object):
def ModifyMain(self, main): # note that self is *this* object; main is the object passed in, which was self in the caller
#Note case - main, not Main
main.A()
def run():
M = Main()
M.B()
if __name__=="__main__": # this will be true if this script is run from the shell OR pasted into the interpreter
run()
Your names all flout the usual python conventions found in PEP8, which is a pretty good guide to python style. I have left them as they were in your code, but don't copy the style in this example - follow PEP8.

Passing an argument when starting new QThread() in PyQt

I have a multi-threaded application written in Python in which one thread "takes care" of the GUI, and the other is the worker thread. However, the worker thread has two main functions (or so to say two main jobs), and I need to tell the run function which job exactly to do.
So what I had in mind was to create a run function in the worker thread which will take one parameter (save for "self). The parameter will either be "create" or upload. Without further ado, here's the somewhat-code that I have so far:
GUI.py
class GUI(QMainWindow):
def __init__(self, parent=None):
super, etc
self.worker = worker.Worker()
def create(self):
self.worker.start()
def upload(self):
self.worker.start()
Worker.py
class Worker(QThread):
def __init__(self, parent=None):
super, etc
def run(self):
self.create_data() # OR self.upload_data(), depends
So the question is, how can I tell worker.start() which function I want it to perform? I realize one could directly use worker.run() method, but I was told by the "Rapid GUI development with PyQT" never to call worker.run() directly, and always to use worker.start().
The start method of QThread doesn't accept arguments. However, you've inherited QThread so you're free to customize it at will. So, to implement what you want, just pass arguments into the constructor of Worker.
Here's your code sample slightly modified to show this in action:
class Worker(QThread):
def __init__(self, do_create_data=True, parent=None):
super(QThread, self).__init__()
self.do_create_data = create_data
def run(self):
if self.create_data:
self.create_data()
else:
self.upload_data(), depends
Eli Bendersky's answer is correct, however the order of arguments appears wrong.
If you call the Worker class like this:
The argument order that worked for me:
def __init__(self, parent=None, do_create_data=True):
The order shown in Eli Bendersky's answer produced this error message for me:
TypeError: QThread(QObject parent=None): argument 1 has unexpected type 'str'
Not sure why, but I'm sure someone can help explain.

how can I lock entire class

I have the following pseudo code:
class A:
mutex lockForB
class B:
def __init__(self, A): //the type of A is class A
lock(A.lockForB)
# ...
unlock(A.lockForB)
# other function have the same locking
I understand from oop point of view it is very bad idea to use such design, but if I create lock inside class B I will not be able to put lock on creator of the class B. Is there any better design for this? Thanks in advance.
I have no idea what you're trying to accomplish. It's unlikely that a class level lock is what you want but your pseudocode is not so far from the actual code so I'll just fill in the blanks. Honestly, without some idea what you're attempting to synchronize access to it's going to be a challenge to help you.
class A:
lockForB = threading.RLock()
class B:
def __init__(self):
with A.lockForB:
# do init stuff
def othermethod(self):
with A.lockForB:
# do other stuff
So that code will work. lockForB is just a class level attribute on A so it is shared between all instances of A. However, in cases where I've seen folks use class level locks like this it is usually to prevent the class that owns the lock from being put into an inconsistent state where you have 2 seemingly unrelated classes sharing a lock.
Without context to help understand what you're attempting to synchronize access to it's really hard to tell you why this couldn't be written like this:
class C:
lock = threading.RLock()
def __init__(self):
with self.lock:
# do stuff
def othermethod(self):
with self.lock:
# do other stuff
In general you should put locks only around the boundaries of critical sections or the use of shared resources. You should consider what it is you're trying to protect from simultaneous access and protect it. If, for instance, class A has a Queue into which items are placed and read from, then it's the access to this particular resource you should protect. Since OOP dictates that this kind of resource should only be accessed by the class methods, only class A should protect it:
class A(object):
def __init__(self, *args, **kws):
# do the initialization
self._my_queue = Queue()
self._lock = Lock()
def do_something(self):
# do initial calculations
self._lock.acquire()
item = self._my_queue.get()
self._lock.release()
# do other things
Hence forth, class B should call class A methods and it will be thread safe. If class B has its own critical sections It's quite alright to use more than a single lock:
class B(object):
def __init__(self, *args, **kws):
# do the initialization
self._lock = Lock()
self.a = A()
def do_something_with_a(self):
# initial calculations
self._lock.acquire()
# Critical section
result = self.a.do_something()
# do something with result
self._lock.release()
# continue the code
This way each class protects its own critical sections and shared resources and there's no need to break the class interface.
If you need to protect the C'tor of a class then you either need a global lock for the module, created and initialized outside the scope of the class, or to add the lock to the Class object (like a static member in C++ and Java) rather than the instance itself:
class B(object):
def __init__(self, *args, **kws):
if not hasattr(self.__class__, "_lock"):
self.__class__._lock = Lock()
# works with Python 2.6+ for earlier version use try-finally
with self.__class__._lock:
# Your initialization
This will protect your C'tor

Categories