Having mulitple classes inside a class python3? - python

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.

Related

Calling a method from all the instances of a class

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.

How do you decide which level a function should be at in python?

I have a file called file_parsers.py and it contains the following class:
class FileParser():
def __init__(self, file_text):
self.file_text = file_text
def do_something(self):
my_value = func_with_no_state()
I'm not sure what questions to ask when deciding whether func_with_no_state() should be inside the class or outside of the class as a file-level function?
Also, is it easier to stub this function when it is at a file-level or inside the class?
So... Does any other class use func_with_no_state? If not, it should be hidden within FileParser. If something else does use it, you have a bigger question. If OtherClass uses func_with_no_state pretty frequently (on par with FileParser) then it would be a good idea to keep func_with_no_state outside so that both classes can use it. But if FileParser is by far the main user, then OtherClass could just pull the function from FileParser's definition.

Keeping classes loosely coupled and sharing data

I've been working in python on a project where I have a GUI which I split up a bunch of the work between classes. I don't know a lot of the best practices for passing data around between classes, and I've frequently run into the issue, where I have to implement something, or change something for work, and I've resorted to making a lot of the classes objects of another class in order to give it the data I need.
Any ideas or suggests would be greatly appreciated on how to keep my classes independent for later modification and still pass the relevant data around without affecting interfaces too much?
As an example
class Window():
def __init__(self, parent=None):
self.parent = parent
def doStuff(self):
#do work here
class ParseMyWork(Window):
def __init__(self, parent=None):
self.parent=parent
I often find myself doing stuff like the above giving objects to class Window
or simply inheriting everything from them as in ParseMyWork
There must be better and cleaner ways of passing data around without making my classes utterly dependent on eachother, where one little change creates a cascade effect that forces me to make changes in a bunch of other classes.
Any answers to the question don't necessarily have to be in python, but it will be helpful if they are
If I'm understanding your question correctly, I would say that inheritance is not necessary in your case. Why not give ParseMyWork a function for dealing with a specific Window task?
class Window():
def __init__(self, parent=None):
self.parent = parent
def doStuff(self):
#do work here
class ParseMyWork():
def __init__(self, parent=None):
self.parent=parent`
def doWindowActivity(self, window):
window.doStuff
Then you can use the function like this
work_parser = ParseMyWork()
window = Window()
work_parser.doWindowActivity(window);
That way you can use your work_parse instance with any window instance.
Apologies in advance for my Python, it's been a while so if you see any rookie mistakes, do point them out.
Keep it simple.py:
def doStuff(window):
#do work here
return window
def parseStuff(stuff):
pass
really.py:
from simple import doStuff, parseStuff
def really_simple(window):
okay = doStuff(window)
return parseStuff(okay)
don't complicate the class:
from really import really_simple
really_simple(window)
imo: classes are overly complicated objects, and in a lot of cases more confusing than they need to be, plus they hold references and modify stuff, and can be difficult to decouple once they have been tied to other classes. if there isn't a clear reason why a class needs to be used, then it probably doesn't need to be used.
Classes are super powerful, so it's good you're getting started with em.
Discalimer: Haven't worked in python for a while now, so things might not be exact. The general idea still applies though.
Getting into your question now:
I would say the best way to achieve what you want is to create an instance of the first object where you will extract information from.
Now when creating a class, it's vital that you have attributes within them that you will want to be stored within it that you would like to retrieve once the class is instantiated.
For example, using your Window class example above, let's say that you have an attribute called resolution. It would look something like this:
class Window():
def __init__(self, parent = None):
self.parent = None
self.resolution = '40x80'
Now the resolution information associated with your Window class is forever part of any Window class instance. Now, the next step would be to create a get method for resolution. This should be done as follow:
class Window():
def __init__(self, parent = None):
self.parent = None
self.resolution = '40x80'
def getResoultion():
return self.resolution
Now, the reason we created this get method is because we can now set a variable to the information that is returned with it.
So let's say that you have everything associated with your Window class in its own file (let's say the file name is called Window.py). In a separate file (let's call it main.py), you can do the following:
import Window
windowInstance = Window()
windowResolution = windowInstance.getResolution()
If you print out the variable windowResolution, you should get that 40x80 printed out.
Now, as a side note, I do believe it is possible to get the information associated with an attribute with an instance of a class by simply doing something like
windowResolution = windowInstance.resolution
but that is bad practice in general. The reason, in a nutshell, is because you are now exposing attribute names of your class which you do not want to do because it makes it easy for a person outside of your code to learn the name where that information is held and change it. This can then lead to a myriad of other problems when it comes to making an overall program work. That is why it is best practice to use getters and setters. I already showed what getters are. Simply a get method for attributes. Setters, as you can probably assume, allow for one to set the information of an attribute to something else. Now you might say "Gabe, if we can create setter methods, what's the point of it if they just change it". My answer to that is to not give a setter method to all attributes. For attributes you don't mind for a person to change, give it a setter method, but for attributes you do not want any outside users to touch, simply don't create a setter method for it. Same goes with getter methods too. Users don't need to see all of the information of all attributes that makes your program work. Here's a better explanation: https://en.wikipedia.org/wiki/Mutator_method
Now, back to your example. Now let's say you have your ParseMyWork class in its own file like we did with your Window class, and let's say that ParseMyWork needs the resolution info from Window class. You can do the following :
import Window
import ParseMyWork
windowInstance = Window()
windowResolution = windowInstance.getResolution()
parseInstance = ParseMyWork(windowResolution)
This will only pass the window resolution information associated with your Window class. Hope this helps.

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

Parallel Subclassing in Python? Using Subclasses in a Subclass

I'm trying to make my program extensible. It's for a generic card game that will play multiple types of games.
I have a generic server, let's call it class GenericServer. It imports classes like Cards, Players, Containers, etc.
I also have a game specific server class that is a subclass of GenericServer, let's call this one MagicServer.
What I'd like to do is have the MagicServer load game specific versions of the classes imported by GenericServer.
class GenericServer(object):
# imports Cards(object), Players(object), Containers(object)
class MagicServer(GenericServer):
# imports MagicCards(Cards), MagicPlayers(Players), MagicContainers(Containers)
The plan is to have multiple game specific servers all as subclasses of GenericServer but also with their own versions of Cards, Players, Containers etc. I've considered just breaking the servers up individually, but since they share so much of the same code I would like to subclass them from GenericServer.
Any suggestions on how to work this out?
is the server generating the cards, players, etc. or just serving/using them?
if the first... then the server class doesn't need to know what kind of card, player, etc. is used. Something else will create it and pass it to the server, who will use it using the standard Card (e.g.) API. This might be a lot easier to maintain and build.
But, if the second... then you could do it with class variables:
class Cards(object):
pass
class MagicCards(Cards):
pass
class GenericServer(object):
cards = Cards
def createCards(self):
return self.cards()
class MagicServer(GenericServer):
cards = MagicCards
gs = GenericServer()
ms = MagicServer()
gs.createCards()
<__main__.Cards at 0x3df6048>
ms.createCards()
<__main__.MagicCards at 0x3df6080>
These don't HAVE to be class variables - they could also be passed into the init function.
class GenericServer2(object):
def __init__(self, cards):
self.cards = cards
def createCards(self):
return self.cards()
gs2 = GenericServer2(Cards)
ms2 = GenericServer2(MagicCards)
gs2.createCards()
<__main__.Cards at 0x3ee5a58>
ms2.createCards()
<__main__.MagicCards at 0x3ee5470>
Which one to use? It really doesn't matter that much. The first is probably more straightforward if you are actually subclassing GenericServer a lot. If you are just using subclassing to differentiate the classes easily, the second is easier, and you can simulate the previous behaviour with factory functions:
def MagicServer2():
return GenericServer2(MagicCards)
etc.
You don't need to subclass everything, why not just subclass the generic server, then have instances of the other classes you need within magic server.
For example:
class MagicServer(GenericServer):
def __init__(self):
self.cards = Cards()
self.players = Players()
self.containers = Containers()
This way your magic server class has a unique Cards instance to use.

Categories