I have to make unit-test for circle in python, but for the life of me cant figure out why I am getting this error :
Traceback (most recent call last):
File "c:\Users\User\Desktop\Domaci\Preadvanje 8\circle_unittest.py", line 6, in test_area
self.assertEqual(circle.area (2),12.564)
File "c:\Users\User\Desktop\Domaci\Preadvanje 8\class_circle.py", line 5, in area
return (self.radius * self.radius) * 3.141
AttributeError: 'int' object has no attribute 'radius'
Code for circle :
class circle:
def __init__(self,radius):
self.radius = radius
def area(self):
return (self.radius * self.radius) * 3.141
def perimeter(self):
return (2 * self.radius) * 3.141
r = int(input("Input r: "))
newcircle = circle(r)
print ("Area of the circle is: ", newcircle.area())
print("Perimeter of the circle is: ", newcircle.perimeter())
Code for test:
import unittest
from unittest.case import TestCase
from class_circle import circle
class test_circle(unittest.TestCase):
def test_area(self):
self.assertEqual(circle.area (2),12.564)
def test_perimeter(self):
self.assertEqual(circle.perimeter(2), 12.564)
if __name__ == '__main__':
unittest.main()
You are using the method "area" directly without instantiating a new object.
class test_circle(unittest.TestCase):
def test_area(self):
c = circle(2)
self.assertEqual(c.area (2),12.564)
def test_perimeter(self):
c = circle(2)
self.assertEqual(c.perimeter(2), 12.564)
In the above code, we create a circle called "c" first, and then test the method area on it, which fixes the issue.
Related
I run this code:
from manimlib import *
class SquareToCircle(Scene):
def construct(self):
circle = Circle()
self.play(ShowCreation(circle))
self.play(circle.animate.shift(2 * RIGHT), circle.animate.scale(0.25))
It's shortened example from https://3b1b.github.io/manim/getting_started/quickstart.html. However, the circle doesn't shift right as specified with circle.animate.shift(2 * RIGHT) as seen here.
I found a correct way to do both animations at the same time
from manimlib import *
class SquareToCircle(Scene):
def construct(self):
circle = Circle()
self.play(ShowCreation(circle))
self.play(circle.animate.shift(2 * RIGHT).scale(0.25))
https://youtu.be/dwovjxTcvEk
Ive been working on this sample code for a while and cant seem to wrap my head around this seemingly simple error.
The code is as follows:
class area :
r=5
l=2
b=3
def __init__(self,r,l,b):
print "parent constructor"
self.r=r
self.l=l
self.b=b
def __del__(self):
print "parent deconstructor"
def circle(self):
circle_area= 3.14 * r * r
print "area of circle is :",circle_area
def rectangle(self):
rect_area=l*b
print "area of rectangle :",rect_area
obj=area(4,5,4)
obj2=area(2,5,4)
obj.circle()
The error message says :
File "yaa.py", line 18, in circle
circle_area= 3.14 * r * r
NameError: global name 'r' is not defined.
You need to use the self for refering class attributes:
def circle(self):
circle_area= 3.14 * self.r * self.r
print "area of circle is :",circle_area
In case you want to use the r within the class, not the instance you have to use the name of the class then:
def circle(self):
circle_area= 3.14 * area.r * area.r
print "area of circle is :",circle_area
You probably need to change your method circle(self) from
circle_area= 3.14 * r * r
to
circle_area= 3.14 * self.r * self.r
because r is an attribute of the class, not a global variable.
The same goes for your method rectangle(self):
rect_area = self.l * self.b
This question already has an answer here:
Python- how to get list of self variables in a class consist of N-self
(1 answer)
Closed 6 years ago.
I am using mesa for my program. I am trying to execute my Model Class, but I got AttributeError from the Agent Class.
This is my script:
class ComtrModel (Model):
""" A model with some number of Agents"""
def __init__(self,N):
self.num_agents = N
self.schedule = RandomActivation(self)
for i in range (N):
a = CommuterAgent(i)
self.schedule.add(a)
class CommuterAgent (Agent):
def __init__(self, model):
self.famsize = famsize
self.distance = distance
self.update_need = None
def step(self):
if self.distance >= 10000:
self.update_need = self.update_need()
return
def update_need (self, famsize):
if self.famsize :
self.famsize = famsize
return
prob_need()
How to get variables of each agent? I need to check it to make sure the model run properly.
So far this is my code to execute (on interactive session):
from src.ComtrModel import *
model = ComtrModel(5)
for i in range (10):
model.step()
for key, value in CommuterAgent.step(model):
print(key, value)
EDIT : But it returns
Traceback (most recent call last):
File "C:src/__init__.py", line 3, in <module>
from src.ComtrModel import *
File "C:\src\__init__.py", line 9, in <module>
for key, value in CommuterAgent.step(model):
File "C:\src\ComtrModel.py", line 40, in step
if self.distance >= 10000:
AttributeError: 'ComtrModel' object has no attribute 'distance'
I also have tried something like this:
>>> hi_obj = hi()
>>> hi_obj.__dict__.keys()
But it only works for single object
def __init__(self, model):
self.famsize = famsize
self.distance = distance
self.update_need = None
Doesn't look correct. You don't pass famsize and distance as parameters.
I'm trying to teach myself how to use classes and I'm trying an example I found in a book that asks you to create two classes and then print out some information. Here is my code:
import math
import turtle
import urllib.request
class Shape:
def __init__(self,x=0,y=0):
self.x = x
self.y = y
def calc_area(self):
pass
def calc_perim(self):
pass
def get_shape_type(self):
return "s"
def to_string(self):
return "%s %f %f" % (self.get_shape_type(), self.x, self.y)
def get_draw_params(self):
return [self.x, self.y]
class Circle(Shape):
def __init__(self,x=0,y=0,rad=0):
super().__init__(x,y)
self.radius = rad
def calc_area(self):
area = math.pi * self.radius * self.radius
return area
def calc_perim(self):
perim = 2 * math.pi * self.radius
return perim
def calc_circumference(self):
return self.calc_perim()
def get_shape_type(self):
return "c"
def to_string(self):
return "%s %f %f %f" % (super().to_string(), self.radius, self.calc_area(),self.calc_perim())
def get_draw_params(self):
result = super().get_draw_params()
result.extend([self.radius])
return result
cir = Circle(0,0,150)
print(cir)
When I try to run it, it prints this:
<__main__.Circle object at 0x103d19ef0>
I'm not sure what I'm doing wrong when I'm calling the Circle class. I was hoping that after putting in the values that the init function asks for, there would be some data to print out. Any help would be greatly appreciated.
Try calling the to_string() method that you added to your classes:
>>> cir = Circle(0,0,150)
>>> print(cir)
<__main__.Circle object at 0x7fba2851b400>
>>> print(cir.to_string())
c 0.000000 0.000000 150.000000 70685.834706 942.477796
If you are wanting a customised string representation, try adding __unicode__() and/or __str__() methods to your classes:
def __str__(self):
return self.to_string()
Now you can do this:
>>> c = Circle(0,0,150)
>>> print(c)
c 0.000000 0.000000 150.000000 70685.834706 942.477796
It's actually quite right, this is how python prints your object,
if you want your print(object) print something else, define __str__ method in your class, something like this (it should return an string):
class Circle(Shape):
# your stuff
# ...
def __str__(self):
return "radius: " + self.radius
cir = Circle(0,0,150)
print(cir)
# radius: 150
There is nothing wrong with what you did. Everything is working fine.
This: <__main__.Circle object at 0x103d19ef0>
is indicating to you have you have an object of Circle. So, if you add this:
print(cir.calc_area())
You will end up getting the area result you expect.
Furthermore, a neat bit of information that can help you is if you want to find out more information about what is inside your objects, you can do this:
print(dir(cir))
This will tell you what is housed inside your 'cir' object and you will also see that your methods you created should be there as well. Always handy to find out what is available to you even when you import other modules when you dive deeper in to Python.
Documentation on dir
Well, that is the default representation of a Circle object when you print it.
Now you can call the methods of cir, like
print(cir.calc_area())
I am trying to write a script contains some classes and save for example as model.py.
import numpy as np
from scipy import integrate
class Cosmology(object):
def __init__(self, omega_m=0.3, omega_lam=0.7):
# no quintessence, no radiation in this universe!
self.omega_m = omega_m
self.omega_lam = omega_lam
self.omega_c = (1. - omega_m - omega_lam)
#self.omega_r = 0
def a(self, z):
return 1./(1+z)
def E(self, a):
return (self.omega_m*a**(-3) + self.omega_c*a**(-2) + self.omega_lam)**0.5
def __angKernel(self, x):
return self.E(x**-1)**-1
def Da(self, z, z_ref=0):
if isinstance(z, np.ndarray):
da = np.zeros_like(z)
for i in range(len(da)):
da[i] = self.Da(z[i], z_ref)
return da
else:
if z < 0:
raise ValueError(" z is negative")
if z < z_ref:
raise ValueError(" z should not not be smaller than the reference redshift")
d = integrate.quad(self.__angKernel, z_ref+1, z+1,epsrel=1.e-6, epsabs=1.e-12)
rk = (abs(self.omega_c))**0.5
if (rk*d > 0.01):
if self.omega_c > 0:
d = sinh(rk*d)/rk
if self.omega_c < 0:
d = sin(rk*d)/rk
return d/(1+z)
Then I want to call Cosmology class into another script, but I get the following error:
>>>from model import Cosmology as cosmo
>>>print cosmo.a(1.)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method a() must be called with Cosmology instance as first argument (got int instance instead)
I don't quite understand what the problem is!! Any tips??
You are trying to call an instance method from a class. In order to use the a() method, you need to create an instance of the Cosmology class:
>>>from model import Cosmology
>>>cosmo = Cosmology()
>>>cosmo.a(1.)
0.5
Or, if you want a() to be a class method, you need to decorate it with the #classmethod decorator - see here for more details.