Calling a method from all the instances of a class - python

This question may sound a little weird, but I have been unable to find the answer so far, and I decided to ask here:
Is there a way to call a method from all the instances of a class without having to loop through each and every single instance manually?
Example:
Normally, I would do something like this:
instList = []
class SomeClass:
def __init__(self,*args,**kwargs):
#init stuff
instList.append(self)
def theThing(self):
#do the thing
def allTheThings(il):
for inst in il:
inst.theThing()
allTheThings(instList)
This works pretty well normally, but it doesn't seem very efficient. Is there some way to streamline this into one or two lines of code?
Something like this:
class SomeClass:
def __init__(self,*args,**kwargs):
#init stuff
def theThing(self):
#do the thing
SomeClass.instances.theThing()
or this:
class SomeClass:
def __init__(self,*args,**kwargs):
#init stuff
def theThing(self):
#do the thing
instancesOf(SomeClass).theThing()
This would be really helpful, as I plan on using this in many different ways: auto-killing everything at the end of a game, detecting various polygon-shaped buttons being clicked, anything that involves calling a single method on a bunch of instances.

Related

Extract method and insert call after original method call

I'm using PyCharm and I'm trying to do some refactoring but don't see how I'm able to do this in a fast and reliable way.
I have a method that does too many things and I want to extract a part into another method. The extracted method should not be called in the method it was extracted though, but rather in the calling method.
Current state
class User():
def doStuff(self):
calculateA()
calculateB()
calculateC()
def callerA():
# do other things before
obj.doStuff()
def callerAA:
# do other things before
obj.doStuff()
#... and many more methods calling doStuff method
Wanted
class User():
def doStuff(self):
calculateA()
def doOtherStuff(self):
calculateB()
calculateC()
def callerA():
obj.doStuff()
obj.doOtherStuff()
def callerAA:
obj.doStuff()
obj.doOtherStuff()
#... and many more methods calling doStuff method and doOtherStuff
# Now I'll be able to create this new method only doing a subset of the original method
def aNewMethod:
obj.doStuff()
Is this possible to do with PyCharm? Been playing around with the refactoring without any luck. Extracting into a method is the easy part I suppose but the method call will end up in the wrong place. If it's possible in Intellij I have a license for that as well so I can just switch.
there is no such option. You are welcome to submit a feature request at https://youtrack.jetbrains.com/issues/PY
Information on how to use YouTrack: https://intellij-support.jetbrains.com/hc/en-us/articles/207241135-How-to-follow-YouTrack-issues-and-receive-notifications
Step1: Extract two new methods into your User class
This:
class User():
def doStuff(self):
calculateA()
calculateB()
calculateC()
Becomes:
class User():
def doStuff(self):
newMethodA()
newMethodB()
def newMethodA(self):
calculateA()
def newMethodB(self):
calculateB()
calculateC()
Step 2: Inline doStuff method
class User():
def newMethodA(self):
calculateA()
def newMethodB(self):
calculateB()
calculateC()
def callerA():
newMethodA()
newMethodB()
def callerAA():
newMethodA()
newMethodB()
Step 3: Rename methods

Having mulitple classes inside a class python3?

I'd like to do something like this:
Robot.GyroController.getLatestMeasurement()
Is there a way to do this?
More specifically I wanted to do this:
robot = Robot.__init__(arguments)
latesMeasurement = robot.GyroController.getLatestMeasurement()
Is this valid python? And most importantly, is it possible to do so?
I need to do a LEGO competition. I can use whatever programming language that I want to and so I figured I'd write a library to get slightly better abstraction over the existent one (also to practice python as I want to get into tensorflow)
I have a class called robot. This class is initialized with references to all the motors/sensors the robot has.
From there, I want some subclasses (or maybe something else?) that can control motors, sensors, and do some other fancy stuff.
Instead of passing robot (that contains references to motors/sensors) every time I use motors/sensors, I figured that I could do something like this.
PS. I am coming from OOP, and still learning python, so please, it is my intention to improve the question as best as I can. Please give me a chance.
From what i read, you want to have a Robot Class that has multiple Motor's class or something like that, maybe this could work as a hint on how that could be done:
class Motor:
def __init__(self, motor):
self.motor = motor
def go_slow(self):
self.motor.setval = 100
def go_fast(self):
self.motor.setval = 255
class Robot:
def ___init___(self, reference_motor1, reference_motor2):
self.motor1 = Motor(reference_motor1)
self.motor2 = Motor(reference_motor1)
def go_straight_slow():
self.motor1.go_slow()
self.motor2.go_slow()
def go_straight_fast():
self.motor1.go_fast()
self.motor2.go_fast()
here's a dummy example on how your code maybe look like if you wanna do it object oriented.
Edit:
assuming that you already got the class that "MotorController"
class MotorController:
def __init__(self):
pass
def goStraight():
pass
class Robot:
def ___init___(self):
self.motor_controllers = [] #List for storing all motors
def add_motor_reference(self, reference):
self.motor_controllers.append(MotorController(reference))
#Appends new motors to the list
def go_straight(self):
for motor_controller in self.motor_controllers:
motor_controller.goStraight()
#Executes for the "goStraight" function on every motor in the list
Edit:
If you want to add the motors on the constructor of the class you could do something like:
class Robot:
def ___init___(self, *args):
self.motor_controllers = [] #List for storing all motors
for motor in args:
self.motor_controllers.append(MotorController(motor))
#Here every motor reference you pass will be automatically added in the list of motor controllers.

Implement same methods in different classes

I really don't know how to word this problem, so I'll try to explain it with an example.
Let's say I have three GUI classes:
Base Surface class
Detailed Surface Class
Sprite Class
All of them are independent of each other, no inheritance among them.
Now I have a function "drag()" that makes a surface/sprite dragable, and I want to implement this function as a method for all three of them.
Since it's the exact same code for all implementations I find it annoying, cumbersome and bad practice to rewrite the code.
The only thing I came up with so far was to make a saperate class for it and inherit this class. But that also doesn't seem to be the way to go.
I'd be very thankfull for some advice.
EDIT
Another example with a slightly different setup - I have the following classes:
BaseSurface
Dragable
Resizable
EventHandler
Only the first one is independent, the others depend on the first (must be inherited).
The end user should, without any effort, be able to choose between a simple BaseSurface, one with that implements dragable, one with resizable, one with eventHandler, and any combination. By "without any effort" I mean the end user should not have to make e custom Class and inherit the desired classes plus call the appropriate methods (init, update, ...) that some classes share.
So what I could do is make a class for every possible combination, eg.
"BaseSurfaceDrag", "BaseSurfaceDragResize", ...
which will get messy really quickly. Whats a different and better approach to this?
This is exactly the kind of case that you should use a parent class for. In both cases it looks like your parent class (logically) should be something like:
class Drawable(object):
def drag(self, *args, **kwargs):
"""Drag and drop behavior"""
# Your code goes here
Then each of your other classes inherits from that
class BaseSurface(Drawable):
# stuff
class DetailedSurface(Drawable):
# stuff
class Sprite(Drawable):
# stuff
In the second case what you have are interfaces, so you could logically do something like:
class DragInterface(object):
"""Implements a `drag` method"""
def drag(self):
"""Drag and drop behavior"""
# Your code goes here
class ResizeInterface(object):
"""Implements a `resize` method"""
def resize(self):
"""Drag and drop resize"""
# Code
class EventHandlerInterface(object):
"""Handles events"""
def handle(self, evt):
# Code
class MyNewSurface(BaseSurface, DragInterface, ResizeInterface):
"""Draggable, resizeable surface"""
# Implement here

Self-modifying Python class

I would like to modify an initializer of a class at run-time. Are there any potential catches with a code like this? I'm new into decorators so not really sure.
class Object:
def __init__(self):
print "do something"
#classmethod
def modify(cls, f):
__init___old = cls.__init__
def __init__(self):
__init___old(self)
f(self)
cls.__init__ = __init__
return f
#Object.modify
def f(self):
print "do something else"
Apart from confusing people who aren't used to python's powerful meta programming facilities, things like you do should work fine. Class is modifiable is a feature of python.
However, I would suggest to find a more conventional way to do what you needed to do, meta programming causes the source code on file to no longer match what a cursory inspection of the code suggest that the code do, so it is not very good for readability. For this particular case, you could append to a list in a class variable to be called in a loop in __init__.
The only catch you may or may not experience is that if you use a python optimizing compiler, e.g. psyco, pypy, using dynamic features like this may cause them to not be able to optimize things as well as they would otherwise be able to.
Rather than redefining __init__ like this, make your class keep a list of functions (which can be augmented) that should be executed at object initialization time.
class Object:
obj_initializers = []
def __init__(self):
print "do something"
for f in self.obj_initializers:
f(self)
#classmethod
def add_initializer(cls, f):
cls.obj_initializers.append(f)
def f(self):
print "do something else"
Object.add_initializer(f)
In your code, f isn't actually modified; you are just abusing the decorator syntax to execute another function with f as an argument.

Python global/package alias implementation class

I have that strange feeling this is an easy question.
I want to be able to "alias" a class type so i can swap out the implementation at a package level. I dont want to have X amount of import X as bah scattered throughout my code...
Aka. How can I do something like the below:
class BaseClass(object):
def __init__(self): pass
def mymthod(self): pass
def mymthod1(self): pass
def mymthod2(self): pass
class Implementation(BaseClass):
def __init__(self):
BaseClass.__init__()
Seperate package...
#I dont want thse scattered through out modules,
#i want them in one place where i can change one and change implementations
#I tried putting it in the package init but no luck
import Implementation as BaseClassProxy
class Client(BaseClassImpl):
def __init__(self):
BaseClassImpl.__init__(self)
In any file (where this fits best is up to you, probably wherever Implementation was defined):
BaseClassProxy = Implementation
Since classes are first class objects in Python, you can pretty much bind them to any variable and use them the same way. In this case, you can make an alias for the class.
just put something like
BaseClassProxy = Implementation
in the module, then do:
from module import BaseClassProxy

Categories