I'm writing a class similar to this one how can I pass values (w,v) to the def q func
class A():
def EM (self,a,b):
self.a=a
self.b=b
w=a+b
print(w)
def number(self,c,d):
self.c=c
self.d=d
v=c-d
print(d)
def q (self,v,w) ##problrm here
qq=v+w
print(qq)
Firstly it helps if you format your code properly as shown:
class A():
def EM (self,a,b):
self.a=a
self.b=b
w=a+b
print(w)
def number(self,c,d):
self.c=c
self.d=d
v=c-d
print(d)
def q (self,v,w) ##problrm here
qq=v+w
print(qq)
But to answer your question you would use the results for EM and number as shown
instance = A()
result = instance.q(instance.EM(a, b), instance.number(c, d))
Because you want to use multiple method results as parameters you have to do it outside of those methods although you could create a new method to make it look better like
class A():
def EM (self,a,b):
self.a=a
self.b=b
w=a+b
return w
def number(self,c,d):
self.c=c
self.d=d
v=c-d
return d
def q (self,v,w)
qq=v+w
return qq
def doThisThing(a, b, c, d):
return self.q(self.EM(a, b), self.number(c, d))
Notice how I've changed the prints to returns as instead of displaying the result to the console we want to pass the result to the caller. If you wanted to now display the result you could use
print(instance.doThisThing(a, b, c, d))
Try this out:
a = A()
a.q(w= '''w''',v= '''v''')
Related
So let's say I have this code structure:
class Parent:
def __init__(self, a, b, c):
self.a = a,
self.b = b
self.c = c
#classmethod
def from_string(cls, some_string):
if some_string == 'duh':
return cls(a=5, b=6, c='banana')
else:
return cls(a=0, b=0, c='chicken')
def method_1(self):
#do something
def method_2(self):
#do something else
class FirstChild(Parent):
def __init__(self, a, b, c):
super().__init__(a, b, c)
def child_specific_method(self):
#do something
class SecondChild(Parent):
def __init__(self, a, b):
super().__init__(a, b)
def some_other_method(self):
#do stuff
My thinking was that I want both subclasses to have access to methods of the Parent class, but also extend its functionality. At the same time I want the Parent class to instantiate with different parameters based on the class method.
Now I'm confused as to how I would create instances of child classes? Or, more precisely, how would I create child instances when there can be different versions of the parent class?
I like to pass a function which has 2 arguments to a class where 1 of the arguments are "predefined". When I call the function from within a class instance, I only want to give the second variable (because I already defined the first). Example:
def my_fun(a, b):
return a+b
class MyClass():
def __init__(self, fun):
self._fun = fun
def class_function(self, c):
return self._fun(c)
instance = MyClass(my_fun(a=5.0))
print(instance.class_function(10.0))
Is this possible?
Use partial from functools module.
from functools import partial
def my_fun(a, b):
return a + b
class MyClass():
def __init__(self, fun):
self._fun = fun
def class_function(self, c):
return self._fun(c)
instance = MyClass(partial(my_fun, 5.0))
print(instance.class_function(10.0))
I'm trying to use the cooperative multiple inheritance pattern to resolve a problem. A very simplified version of my python 2.7 code looks like this:
class Base1(object):
def __init__(self, a, b):
self.a = a
self.b = b
def to_tuple(self):
return self.a, self.b
def to_string(self):
return '%s.%s' % self.to_tuple() # (1)
class Base2(object):
def __init__(self, c, d):
self.c = c
self.d = d
def to_tuple(self):
return self.c, self.d
def to_string(self):
return '%s-%s' % self.to_tuple() #(2)
class MyMixin(Base1, Base2):
def __init__(self, a, b, c, d):
Base1.__init__(self, a, b)
Base2.__init__(self, c, d)
def to_tuple(self):
return Base1.to_tuple(self) + Base2.to_tuple(self)
def to_string(self):
return '{}: {} '.format(Base1.to_string(self), Base2.to_string(self))
mix = MyMixin('a', 'b', 'c', 'd')
print(mix.to_string())
After writing this code, I was expecting the result:
a.b: c-d
but the code fails. When the line #(1) is run, self is a MyMixin class, not a Base1 class, so to_tuple returns 4 items.
The only way I've found to fix this is to replace the lines #(1) and #(2) above with:
return '%s.%s' % Base1.to_tuple() # (1)
return '%s.%s' % Base2.to_tuple() # (2)
and this feels terribly wrong for a number of reasons.
What am I doing wrong?
Here is what happens. When mix.to_string() is called, first, it calls Base1.to_string(self) passing a mix instance as a self, which means when to_string is called on Base1 it has an instance of MyMixin which returns ('a','b','c','d') on to_tuple call. That's why it fails, cuz tuple contains 4 items and only 2 are required by line #1.
To solve this issue try to avoid inheritance from multiple classes with the same method signatures. Use composition instead.
class MyMixin(object):
def __init__(self, a, b, c, d):
self.base1 = Base1(a, b)
self.base2 = Base2(c, d)
def to_tuple(self):
return self.base1.to_tuple(self) + self.base2.to_tuple(self)
def to_string(self):
return '{}: {} '.format(self.base1.to_string(), self.base2.to_string())
How does one define a class constructor with two possible inputs:
class MSMeshFace(object):
def __init__(self, A=None, B=None, C=None)
def __init__(self, A=None, B=None, C=None, D=None)
So obviously this doesnt work but that's what i would like it to behave as. If someone inputs A,B,C then construct MSMeshFace from those three variables else if someone inputs A,B,C,D then construct it from all four. What's the proper way to do that so that when I call it it looks like this:
newFace = MSMeshFace(A, B, C)
or
newFace = MSMeshFace(A,B,C,D)
and they both work properly but first one creates a "triangular" face and second a "quad". I dont want to do something like newFace = MSMeshFace().Quad(A,B,C,D) if possible.
or should i do something like:
class MSMeshFace(object):
def __init__(self, a= None, b= None, c= None, d= None):
self.a = a
self.b = b
self.c = c
self.d = d
if self.d == None:
triangleFace = MSMeshFace(self.a, self.b, self.c)
return triangleFace
else:
quadFace = MSMeshFace(self.a, self.b, self.c, self.d)
return quadFace
def addData(self, data):
self.data = data
is this a valid way to construct that class?
class MSMeshFace(object):
def __init__(self, A, B, C, D=None):
if D is None:
# build mesh using (A,B,C)
else:
# build mesh using (A,B,C,D)
triFace = MSMeshFace(A,B,C)
quadFace = MSMeshFace(A,B,C,D)
I have a Python class C which should have two pseudo-dicts a and b. The term pseudo-dicts means that the dictionaries don't actually exist and that they are “recomputed” each time a key is accessed.
In pseudocode this would look like this:
class C:
def a.__getitem__(self, key):
return 'a'
def b.__getitem__(self, key):
return 'b'
>>> c = C()
>>> c.a['foo']
'a'
>>> c.b['bar']
'b'
I could implement a class for a and b, but since both have just a few short methods, I wonder whether there is a more elegant and compact way to do this.
Why not just define your own class?
class PseudoDict(object):
def __init__(self, c):
self.c = c
def __getitem__(self, key):
return self.c.somethingmagical()
class C(object):
def __init__(self):
self.a = PseudoDict(self)
self.b = PseudoDict(self)
c = C()
print c.a['foo']
print c.b['bar']
I'm not sure where the values for these 'pseudo-dicts' are coming from, so you'll have to update the __getitem__ method.
Like this?
from collections import defaultdict
class C:
a = defaultdict(lambda:'a')
b = defaultdict(lambda:'b')
c=C()
print c.a['foo']
print c.b['bar']
Or maybe like this for real calculation functions?
from collections import defaultdict
class C:
def __init__(self):
self.a = defaultdict(self.geta)
self.b = defaultdict(self.getb)
def geta(self):
return 'a'
def getb(self):
return 'b'
c=C()
print c.a['foo']
print c.b['bar']