I am trying to pass multiple input entries i as arguments into class Student(). After the last iteration (m), I get a type error. I already tried a for-loop as well, but it didn't work either. Thanks for your help!
class Student():
def __init__(self, d, a, b, c):
self.d = d
self.a = a #name
self.b = b #roll
self.c = c #percentage
return#
def uid(self):
print('UID:', self.d)
def name(self):
print('Name:', self.a)
def roll(self):
print('Roll:', self.b)
def perc(self):
print('Perc:', self.c)
#THIS IS WHAT YOUR INPUT SHOULD LOOK LIKE:
#Peter 405 100
m = input('how many entries? ')
n = 0
while n < int(m):
i = input()
j = i.split()
o = Student(n,*j)
o.uid(), o.name(), o.roll(), o.perc()
n+=1
Student()
The last line - Student() creates an instance of the class without providing any arguments. Hence, Python raises a type error.
Deleting this line (or entering the arguments) will fix the problem.
Related
I got a task on courses: Create Fibonacci generator function and create a decorator to leave only even numbers in this sequence. I tried but had no success. Lower I add a code which I try to create.
def decorator(func):
def inner(*args, **kwargs):
print("start decorator")
value = func(*args, **kwargs)
if a%2==0:
print(a)
return value
print("finish decorator")
return inner
#decorator
def fib(n):
a, b = 0, 1
for __ in range(n):
# if a%2==0:
yield a
a, b = b, a + b
print(list(fib(10)))
Please, help to find a way to solve it.
I am writing a class wherein I want to use a metric to calculate the score. I should be able to pass the metric as an argument based on which I want to calculate a score. Here is the code I have written. Is there a better approach to solving this situation?
class A:
def __init__(self, region):
self.region = region
def metric1(self, a, b):
returns a*b
def metric2(self, a, b, c):
return self.metric1(a, b) + c
def evaluate(self, metric, a, b, c = None):
if metric = 'metric1':
score = self.metric1(a,b)
elif metric = 'metric2':
score = self.metric2(a,b,c)
return score[0]
obj1 = A('XYZ')
obj1.evaluate('metric2', a, b, c)
Furthermore, I want to write another method that would use the output of the evaluate method to do some other calculations. Is this the right approach to writing a class when we have this chain of outputs from previous methods used in subsequent methods? Or, can we leverage decorators here somehow?
You can access method inside a class by className.methodName (A.metric1) or object.methodName (obj1.metric1)
class A:
def __init__(self, region):
self.region = region
def metric1(self, a, b):
return a*b
def metric2(self, a, b, c):
return self.metric1(a, b) + c
def evaluate(self, metric, a, b, c = None):
if metric == A.metric1:
score = self.metric1(a,b)
elif metric == A.metric2:
score = self.metric2(a,b,c)
return score
obj1 = A('XYZ')
print(obj1.evaluate(A.metric1, a=1, b=2)) # 2
print(obj1.evaluate(A.metric2, a=1, b=2, c=3)) # 5
My approach of writing such class.
class A:
def __init__(self, region, a, b, c=None):
self.region = region
self.a = a
self.b = b
self.c = c
def metric1(self):
return self.a * self.b
def metric2(self):
return A.metric1(self) + self.c
obj1 = A('XYZ', 1, 2, 3)
print(A.metric1(obj1)) # 2
print(A.metric2(obj1)) # 5
It says " AttributeError: 'int' object has no attribute 'Factorial' ", how could i tackle it?
I want to use my generator in my function in the same class.
class a:
def __init__(self, n):
self.n = n
def Factorial(self):
res = 1
for i in range(1, self):
res *= i
yield res
def m(self):
s = []
for i in self.Factorial(self):
s.append(i)
return s
print(a.m(100))
Here is a working version:
class a:
def __init__(self, n):
self.n = n
def Factorial(self):
res = 1
for i in range(1, self.n):
yield res
res *= i
def m(self):
s = []
for i in self.Factorial():
s.append(i)
return s
b = a(100)
print(b.m())
There is no problem with using a generator that has been defined in the class in which it is being used.
Your code has a 2 errors:
When you are calling range on Factorial method, you are passing self as range limit instead of self.n + 1, as factorial of a natural number n is defined as: n × (n - 1) × (n - 2) × ... × 2 × 1.
You are calling self.iter which is not valid Python syntax (as you have not defined an iter method to your class). You should use for m in self.Factorial():.
Solve those and your code should work!
In a class,self is the first parameter of the methods. However, you do not have to pass it; it is automatically passed when using the . operator on a class instance (here self and m are instances of the class)
class a:
def __init__(self, n):
self.n = n
def Factorial(self):
res = 1
for i in range(1, self.n):
res *= i
yield res
def m(self):
s = []
for i in self.Factorial():
s.append(i)
return s
print(a(100).m()) # a(100) creates an instance (calls __init__ with param n=100
So I'm very new to writing unit tests and I need some guidance on how to write unit tests for the class I have written.
Any help will be appreciated
Thanks in advance! Also, I want to write the unit tests in pycharm.
class StringProcessor:
def __init__(self, yo="", a="", b="", f=""):
self.yo = yo
self.a = a
self.b = b
self.f = f
def my_first_test(self):
yo = input("Enter your string here")
ya = yo.split()
even = 0
odd = 0
for i in ya:
if len(i) % 2 == 0:
even = even + 1
else:
odd = odd + 1
print("The number of odd words are ", odd)
print("The number of even words are", even)
def my_second_test(self, a, b):
d = a.split()
print("The word", b, "is repeated: ", d.count(b), "times")
def my_third_test(self, f):
d = {}
lst = f.split()
for c in lst:
d[c] = lst.count(c)
for key,value in d.items():
print(key, ":", value)
You have to separate the user inputs from the class to make it testable.
You do not need a class here, just a dict and a few fucntions.
Also, imho user inputs are evil, use sys.argv instead.
class A:
def __init__(self, a: int, b: [str]):
self._foo = a
self._bar = b
def get_foo(self):
return self._foo
def get_bar(self):
return self._bar
def do_that(given):
x = given.get_foo()
x += 10
y = given.get_bar()
y[0] += ' there'
y = ['cool']
given = A(-10, ['test'])
x = A(1, ['hello'])
print(x.get_bar())
How come print(x.get_bar()) prints hello there, instead of 'test' when given is replaced with A(-10, ['test'])? In a similar function like this,
def test(x):
x = 4
return x
x = 1
test(x)
x is replaced with 4 and 4 is actually returned.
In your second bit of code def test(x):, you're overwriting the input to 4, regardless of what you put in by setting x = 4.
In your first bit of code, you're not actually calling the do_that(given): function when you call x.get_bar(), so the ['hello'] will not be overwritten with ['test']. Also, where given is defined as a variable within def get_bar(given):, it is not ever being used.