possible multiple inheritance? - python-3.x

I'm trying to make multiple classes that will use the same set of defintions that already exist in my code.
class FT_Ten(PrinterInterface):
name = "Big Foot"
QueryCmd = "M107"
ActionCmd = "M108"
def __init__(self, device="/dev/ttyACM0"):
self.device = device
def hexformat(self, string):
out = "".join("{:x}".format(ord(x)) for x in string)
return out
def _console_print(self, line):
sys.stdout.write(line)
Theres about 90 more lines of code for this class. I need to add three more classes that share these definitions. The only differences are in the first few lines. Name, QueryCmd, and ActionCmd.
Ive tried simply breaking the the code at the begining of the definitions but im only familiar using a single class at a time.
How can i add more classes and use all the definitions that followed the first?
I've looked here trying to figure this out..
Define methods for multiple classes

Related

Is it possible for an instance of a class within a different class to inherit its variables

I have 2 classes, one does calculations calc and the other sets up and runs setuprun the calculation.
I have multiple instances of the calc class in setuprun to run multiple calculations in one go for each tab. method from here
At the moment they are separate classes but I'd like to inherit variables from setuprun to calc, specifically excelbook and cases, to remove some duplicated code. I have tried various combinations of parent, child and super with no luck.
I guess my question is; is it possible for an instance of a class within a different class to inherit its variables - as i write this, my feeling is not...
Any pointers would be much appreciated. Thanks.
code below:
class calc():
def __init__(self, excelbook, tab, cases):
self.excelbook = excelbook
self.cases = cases
self.tab = tab
def run(self):
print(self.excelbook, self.cases, self.tab)
class setuprun():
def __init__(self, excelbook, cases):
self.excelbook = excelbook
self.gettabs()
runs = [calc(excelbook, t, cases) for t in self.tabs]
for run in range(len(runs)):
runs[run].run()
self.check = runs
def gettabs(self):
self.tabs = list(self.excelbook)
can run with:
a = setuprun('xlsx', 100)
As i write this, my feeling is not... Do not underestimate Python ;)
There is something strange about your code that I don't understand: you are taking the length of the string 'xlsx' to instantiate the calc classes. It just prints
xlsx 100 x
xlsx 100 l
xlsx 100 s
xlsx 100 x
That's fine with me though, but probably not correct in your final application.
After you instantiate the class setuprun, it instantiates 4x a class calc() each time with the same values for excelbook and cases. These two variables are instance variables of the class setuprun.
What you can do is turn them into class variables. After that, you can reference them directly, hence, you do not need to instantiate class calc with the common variables.
Because it is good practice to use capitalized names for classes (to distinguish them from instance variables) I do so in the adapted code below:
class Calc():
def __init__(self, tab):
self.excelbook = Setuprun.excelbook
self.cases = Setuprun.cases
self.tab = tab
def run(self):
print(self.excelbook, self.cases, self.tab)
class Setuprun():
def __init__(self, excelbook, cases):
Setuprun.excelbook = excelbook
Setuprun.cases = cases
self.gettabs()
runs = [Calc(t) for t in self.tabs]
for run in range(len(runs)):
runs[run].run()
self.check = runs
def gettabs(self):
self.tabs = list(self.excelbook)
a = Setuprun('xlsx', 100)
I'm not quite sure if this is what you were looking for, but I do hope it answers your question.

Kivy Mapview: distinguish buttons pressed

Sorry for this noob question, im still learning and I find little documentation for the mapview module.
So for one screen page I have this:
class Mapspage(Screen):
def __init__(self, **kwargs):
self.aboutname="hi"
super(Mapspage, self).__init__(**kwargs)
gl = GridLayout(cols=1)
mapview = MapView(zoom=12, lat=55.6712674, lon=12.5938239)
self.buttons=[]
self.nums=range(0,len(df["name_en"]))
for i in self.nums:
name=list(df["name_en"])[i]
marker = MapMarkerPopup(lat=list(df["latitude"])[i], lon=list(df["longitude"])[i])
self.buttons.append(button(text=list(df["name_en"])[i],on_press=partial(self.pressbutton,num=self.nums[i]),size=(len((df["name_en"])[i])*7*1.05,15),size_hint=(None,None)))
marker.add_widget(self.buttons[i])
mapview.add_marker(marker)
gl.add_widget(mapview)
self.add_widget(gl)
def pressbutton(self,num, *args):
global aboutname
aboutname=(df["name_en"])[num]
chatapp.screenmanager.current = "About"
where I use from functools import partial.
The problem with my approach, despite I made sure the buttons are stored in a different variable (elements of the self.buttons list), and even made sure the numbers them self are stored in a separate list, I cant get to pass the number variable, that distinguishes the buttons (that appear when clicking the maps point), on to the pressbutton function. When I run my attempt I recieve the error, TypeError: pressbutton() got multiple values for argument 'num' where I think all buttons passed on their num variable.
The problem is with the definition of your pressbutton() method and its handling of keyword arguments. You can handle keywords by defining pressbutton() as:
def pressbutton(self, button_instance, num=99):
which defines num as a keyword argument and provides a default value.
Another option is something like:
def pressbutton(self, button_instance, **kwargs):
num = kwargs.pop('num', 99)
which does the same thing.

How to inherit from a class with __init__ and take multiple input parms with default values

I have two classes as follows:
class Buttons():
def __init__(self, dDict):
self.TCT = Tool()
self.dDict = dDict
def btnName(self):
# I will use both self.TCT and self.dDict here
a = self.dDict['setup']
class Switch(Buttons):
def __init__(self, iButtonType, sButtName=None):
self.TCT =Tool()
self.iButtonType = iButtonType
#sButtName being used below ....
I need to instantiate Switch class, but I need to provide dDict so that Buttons class will have the data it is looking for. What is the right way to instantiate the class Switch? I'm not sure how to handle multiple input parms with default data.
python python-3.x
This other possible solution is not an exact match. Both my classes take input parms and one of the classes has a default value set for its input parm.

Trouble working with and updating dictionary using a class and function in Python 3 [Newbie]

I am somewhat new to coding. I have been self teaching myself for the past year or so. I am trying to build a more solid foundation and am trying to create very simple programs. I created a class and am trying to add 'pets' to a dictionary that can hold multiple 'pets'. I have tried changing up the code so many different ways, but nothing is working. Here is what I have so far.
# Created class
class Animal:
# Class Attribute
classes = 'mammal'
breed = 'breed'
# Initializer/Instance Attribrutes
def __init__ (self, species, name, breed):
self.species = species
self.name = name
self.breed = breed
# To get different/multiple user input
#classmethod
def from_input(cls):
return cls(
input('Species: '),
input('Name: '),
input('Breed: ')
)
# Dictionary
pets = {}
# Function to add pet to dictionary
def createpet():
for _ in range(10):
pets.update = Animal.from_input()
if pets.name in pets:
raise ValueError('duplicate ID')
# Calling the function
createpet()
I have tried to change it to a list and use the 'append' tool and that didn't work. I am sure there is a lot wrong with this code, but I am not even sure what to do anymore. I have looked into the 'collections' module, but couldn't understand it well enough to know if that would help or not. What I am looking for is where I can run the 'createpet()' function and each time add in a new pet with the species, name, and breed. I have looked into the sqlite3 and wonder if that might be a better option. If it would be, where would I go to learn and better understand the module (aka good beginner tutorials). Any help would be appreciated. Thanks!
(First of all, you have to check for a duplicate before you add it to the dictionary.)
The way you add items to a dictionary x is
x[y] = z
This sets the value with the key y equal to z or, if there is no key with that name, creates a new key y with the value z.
Updated code:
(I defined this as a classmethod because the from_input method is one as well and from what I understand of this, this will keep things working when it comes to inheriting classes, for further information you might want to look at this)
#classmethod
def createpet(cls):
pet = cls.from_input()
if pet.name in cls.pets:
raise ValueError("duplicate ID")
else:
cls.pets[pet.name] = pet

Having trouble returning through multiple classes in Python

I'm still learning and like to build things that I will eventually be doing on a regular basis in the future, to give me a better understanding on how x does this or y does that.
I haven't learned much about how classes work entirely yet, but I set up a call that will go through multiple classes.
getattr(monster, monster_class.str().lower())(1)
Which calls this:
class monster:
def vampire(x):
monster_loot = {'Gold':75, 'Sword':50.3, 'Good Sword':40.5, 'Blood':100.0, 'Ore':.05}
if x == 1:
loot_table.all_loot(monster_loot)
Which in turn calls this...
class loot_table:
def all_loot(monster_loot):
loot = ['Gold', 'Sword', 'Good Sword', 'Ore']
loot_dropped = {}
for i in monster_loot:
if i in loot:
loot_dropped[i] = monster_loot[i]
drop_chance.chance(loot_dropped)
And then, finally, gets to the last class.
class drop_chance:
def chance(loot_list):
loot_gained = []
for i in loot_list:
x = random.uniform(0.0,100.0)
if loot_list[i] >= x:
loot_gained.append(i)
return loot_gained
And it all works, except it's not returning loot_gained. I'm assuming it's just being returned to the loot_table class and I have no idea how to bypass it all the way back down to the first line posted. Could I get some insight?
Keep using return.
def foo():
return bar()
def bar():
return baz()
def baz():
return 42
print foo()
I haven't learned much about how classes work entirely yet...
Rather informally, a class definition is a description of the object of that class (a.k.a. instance of the class) that is to be created in future. The class definition contains the code (definitions of the methods). The object (the class instance) basically contains the data. The method is a kind of function that can take arguments and that is capable to manipulate the object's data.
This way, classes should represent the behaviour of the real-world objects, the class instances simulate existence of the real-world objects. The methods represent actions that the object apply on themselves.
From that point of view, a class identifier should be a noun that describes category of objects of the class. A class instance identifier should also be a noun that names the object. A method identifier is usually a verb that describes the action.
In your case, at least the class drop_chance: is suspicious at least because of naming it this way.
If you want to print something reasonable about the object--say using the print(monster)--then define the __str__() method of the class -- see the doc.

Resources