simplify multiple consecutive try/except statements - python

I am working on a class that has attributes depending from one another.
When instantiated, the class should try to initiate all the attributes it can but is should skip the ones raising an exception.
Something like this:
def foo:
def __init__(self, a, b, c):
try: self.x = len(a)
except: pass
try: self.y = sum(b)
except: pass
try: self.z = c
except: pass
try: self.v = self.x + self.z
except: pass
try: self.w = self.x + self.y
except: pass
This works but it looks horrible.
Is there a way to simplify this process?
Is there a way to achieve the same result with a cleaner code like the following?
def foo:
def __init__(self, a, b, c):
try:
self.x = len(a)
self.y = sum(b)
self.z = c
self.v = self.x + self.z
self.w = self.x + self.y
except:
continue_to_the_next_line()

Related

Change a self attribute only for one object in a class in Python

I'm stuck on a problem in Python... (i'm an absolute beginner but i need to do a little
environmental science model..)
so the problem is I have:
class C:
def __init__(self, x, y, z):
self.x = x
self.y = self.x * 8
self.z = self.y * 9 + 0.5
self.w = self.z +2
one = C(5,8,12)
two = C(2,12,12)
three = C(1,2,3)
So... i want to change the self.z but only for the object three
(i want it to be self.z = 12 * self.x );
I have to call it in self.w so i can't modify it after my istances...
do you have any suggestion to a beginner?
Thank you so much and have a nice day!
A few notes. First you are not actually using the arguments of y or z that are passed in __init__(self, x, y, z).
To allow on the fly overloading, you may want to break out the individual assignments into their own methods so it is easier to change the behavior you want.
Below you can pass in a custom function that will be applied to the x value when calculating z.
class C:
def __init__(self, x, custum_fn_z=None):
self.x = x
self.y = self.calc_y()
self.z = self.calc_z(custum_fn_z)
self.w = self.calc_w()
def calc_y(self):
return self.x * 8
def calc_z(self, custom_fn_z=None):
if custom_fn_z:
return custom_fn_z(self.x)
return self.y * 9 + 0.5
def calc_w(self):
return self.z +2
to use it:
one = C(5)
two = C(2)
three = C(1, lambda x: 12*x)

Add methods in another method of a same class

I created 2 method (first, last) and a third one (sum); I want the sum of returned value of first and last and then stored in sum; then I want to display the returned value of the sum.
P.S. I am practicing class and object. This problem can be solved using very basic syntax but I want to learn the class and objects. I am telling this cause, you may think that why am I doing this when there are easier way to do that. ;)
Thanks
class Total:
def __init__(self, x, y):
self.x = x
self.y = y
def first(self):
if self.x < 15:
return self.x * self.y
else:
return self.x - self.y
def last(self):
if self.x < 100:
return self.x + 5
else:
return self.x - 6
def sum(self):
pass
# I need help here
# add returned value of first() and last()
p = Total(25, 5)
p.sum()
You can return the first() and last() methods accumulated sum from the sum() method like:
class Total:
def __init__(self, x, y):
self.x = x
self.y = y
def first(self):
if self.x < 15:
return self.x * self.y
else:
return self.x - self.y
def last(self):
if self.x < 100:
return self.x + 5
else:
return self.x - 6
def sum(self):
return self.first() + self.last()
p = Total(25, 5)
print(p.sum())
Output:
50

How to perform value check inside class

So the task is to make a universal Vector class to perform add method whatever(str or int) the x,y values are.
So here is the code that i've tried to execute just to check if try,except somehow works inside a class
class Vector():
def __init__(self,x,y):
self.x = x
self.y = y
def __valuecheck__(self):
try:
self.x + "a"
except TypeError:
return str(self.x)
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return "Vector({},{})".format(self.x,self.y)
a = Vector(1,"a")
b = Vector("a",2)
c = a.__add__(b)
print(c)
The expected output is
Vector(1a,a2)
I've tried different variants, defining classic function e.g. def valuecheck(), as well tried adding try,except to add and init method, but none seem to work. Need your help guys, any tip is very appreciated!
Cheers!
I think I have found the answer.
class Vector():
def __init__(self,x,y):
self.x = x
self.y = y
def __valuecheck__(self):
try:
self.x + "a"
except TypeError:
return str(self.x)
def __repr__(self):
return "Vector({},{})".format(self.x,self.y)
def __add__(self, other):
mvbh = str(self.x), str(self.y) # My Vector Before Hand
myVector = ''.join(mvbh)
ovbh = str(other.x), str(other.y) # Other Vector Before Hand
otherVector = ''.join(ovbh)
final = "Vector({}, {})".format(myVector, otherVector) # Change this to create a new vector
print(final)
a = Vector(1,"a")
b = Vector("a",2)
a.__add__(b)
class Vector():
def __init__(self,x,y):
self.x = x
self.y = y
def __valuecheck__(self):
try:
self.x + "a"
except TypeError:
return str(self.x)
def __add__(self, other):
return Vector(str(self.x) + str(other.x), str(self.y) + str(other.y))
def __repr__(self):
return "Vector({},{})".format(self.x,self.y)
a = Vector(1,"a")
b = Vector("a",2)
c = a.__add__(b)
print(c)

Python fuction stereotyped

Class A has functionA has if. And functionA is repeated by 100 time in out.
In this case, it looks non scene to caluculate if self.z.... each time in called by for in out.
Class A():
def __ini__(self, z)
self.z = z
def functionA(self, a):
if self.z == 1:
b = zFunc1 * a
elif self.z == 2:
b = zFunc2 * a
return b
def out(self):
for i in range(100):
print(self.functionA(i))
So I'm looking for the way to fix functionA in __ini__ like
Class A():
def __ini__(self, z):
self.z = z
functionA < = FIX by (self.z = 2)
"""
def functionA(self, a):
b = zFunc2 * a
reuturn b
"""
Is there solution?
Just make zFunc* another class attribute decided in __init__:
class A:
def __init__(self, z):
self.z = z
self.z_func = zFunc1 if z == 1 else zFunc2
def function_a(self, a):
return self.z_func * a
In fact, in this example you don't even need self.z as an attribute at all.

Implementing a point class in Python

So I'm trying to implement a point class which creates a point and then rotate, scale and translate the point. Here's what I've currently written.
class Point:
'''
Create a Point instance from x and y.
'''
def __init__(self, x, y):
self.x = 0
self.y = 0
'''
Rotate counterclockwise, by a radians, about the origin.
'''
def rotate(self, a):
self.x0 = math.cos(this.a) * self.x - math.sin(this.a) * self.y
self.y0 = math.sin(this.a) * self.x + math.cos(this.a) * self.y
'''
Scale point by factor f, about the origin.
Exceptions
Raise Error if f is not of type float.
'''
def scale(self, f):
self.x0 = f * self.x
self.y0 = f * self.y
'''
Translate point by delta_x and delta_y.
Exceptions
Raise Error if delta_x, delta_y are not of type float.
'''
def translate(self, delta_x, delta_y):
self.x0 = self.x + delta_x
self.y0 = self.y + delta_y
'''
Round and convert to int in string form.
'''
def __str__(self):
return int(round(self.x))
Something in this code is generating an error. Now I haven't implementing error catching and I do have an error method at the top
class Error(Exception):
def __init__(self, message):
self.message = message
But how would I catch the error if a certain variable is not of type float?
Here's one of the if statements I'm using:
def __init__(self, x, y):
if not isinstance(x, float):
raise Error ("Parameter \"x\" illegal.")
self.x = x
self.y = y
if not isinstance(y, float):
raise Error ("Parameter \"y\" illegal.")
self.x = x
self.y = y
But that gets me an indentation error. So how exactly can I print out an error message that says exactly which variable is causing the problem?
If you want to raise an exception, do it in the Point's initializer:
def __init__(self, x, y):
if not isinstance(x, float) or not isinstance(y, float):
raise Error("Point's coordinates must be floats.")
self.x = x
self.y = y
Or convert the coordinates to float:
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
If the variable is not a float, you'll get a TypeError. Pretty much you can 'catch' these error like this;
try:
pass # your stuff here.
except e as TypeError:
print e # this means a type error has occurred, type is not correct.
Also, this would be worth reading for checking for correct types at the start with assert; https://wiki.python.org/moin/UsingAssertionsEffectively

Categories