Original class program:
from Circle import circle
class circle:
def __init__(self,radius=1): #write def __init__(self,radius=1) to set a value
self.radius=radius
# constructer constructs the object and initializes it
def getArea(self):
return(3.142*self.radius*self.radius)
def getPerimeter(self):
return(2*3.142*self.myradius)
Using class:
def main():
c1=circle()
#If below happens
c1.radius=-1
#if above happens then negative value will be returned
c2=circle(5)
c3=circle(3)
print(c1.getArea())
print(c2.getArea())
print(c3.getArea())
main()
I was just trying to learn about classes in python. When I run the program it says that
builtins.AttributeError: 'circle' object has no attribute 'getArea'
I am not able to understand why it is happening.
What about something like this:
from math import pi
class Circle:
def __init__(self,radius=1):
self.radius=radius
def get_area(self):
return pi * self.radius**2
def get_circumvention(self):
return 2 * pi * self.radius
if __name__ == "__main__":
c1=Circle()
#If below happens
c1.radius=-1
#if above happens then negative value will be returned
c2=Circle(5)
c3=Circle(3)
print(c1.get_area())
print(c2.get_area())
print(c3.get_area())
print(c1.get_circumvention())
print(c2.get_circumvention())
print(c3.get_circumvention())
The error you are seeing is probably because you have that weird import statement on top that hides your circle class (you try to call Circle.circle.getArea() that does not exists)
Furthermore:
python coded styles suggest CapsWords for class names and
lowercase for methods and functions.
self.myradius is not defined in __init__ so getPerimeter will fail.
The brackets in the methods are not necessary.
math has pi
To the power is noted as ** (5**2 == 25)
Use the if __name__ == "__main__": construct if you only want to execute when directly run and not on import.
Perimeter -> circumvention
Use the import statement in another python file that you want to use the Circle class in: from whateveryounamedthisfile import Circle. Then you can use Circle like you would in this file.
Your import is pointless. Don't import 'circle' from 'Circle' if you, as the comments have stated. Also, you have not defined the 'myradius' attribute, therefore your 'getPerimeter()' function will not work unless you change that.
Related
I'm learning about classes in Python, particularly about nested classes.
I'm trying to execute the below code and I get an error: int object is not callable, but
I don't understand why!
All I want is to create an object that identify Man, and he has hands, and the hands have their own size, length, etc...
I want to be able to set the hand size and get its value in the most elegant and easy way as possible and nothing work for me... I tried the below code and I really thought it would work but it didn't and now I know that "I Don't know" what to do for real.
class Man:
def __init__(self, name):
self.name = name
self.hand = self.Hand_Object() # Here we reference an Object called
# "hand" to the subvlass "Hand_Object".
def length(self , length):
self.length = length
def handsize(self, size=None): # This "handsize()" function will call the
# subclass function "length()" out from the
# Hand_Object vlass when it will be issued
# in the program.
if size==None:
return = self.hand.length()
else:
self.hand.length(size) # The "length()" function of the "Hand_Object"
# class requires a variable, so when we call
# that function we need to add a variable to it.
class Hand_Object:
def length(self, length=None):
if length == None:
return self.length
else:
self.length = length
def fingers(self, fingers):
self.fingers = fingers
myman = Man('shlomi')
myman.handsize(6)
print(myman.handsize()) # Here I get the error.
The issue is the line self.length = length in Hand_Object. You're overwriting the function length with an integer. You should call the function and the variable something different.
I am trying to test a python method of a file-A which uses a variable in file-A.
My file-A method looks like this:
def rotate(self, rotation):
self.current_face = board.positions[(board.positions.index(self.current_face) + rotation) % 4]
Note: This is inside class A-1 in file-A
The main for file-A looks like this:
if __name__ == '__main__':
inp = Input("input.txt") # create Input object
board = Board(inp.lines[0]) # create board object -----> NOTE
rover_objects(inp.lines[1:]) # create rover objects
process_and_print() # process and print output
So, when I run file-A, it works exactly like I want it to work.
Now, I am trying to test def rotate(self, rotation) in file-A
My test code looks like:
class RoverTest(unittest.TestCase):
def setUp(self):
description = '1 2 N'
moves = 'LMLMLMLMM'
self.testRover = Rover(description, moves)
def test_coordinates(self):
self.testRover.rotate(rotation = 4) -----> Problem
self.assertEqual(self.testRover.current_face, 'N')
The issue is, rotate method in file-A uses the object board in the main in file-A
I am not sure how to pass board to the rotate function from the test.
If I run my test right now, I am thrown an error:
NameError: name 'board' is not defined
How can I fix this error?
If you are writing a class that depends on other classes existing, you should make it accept those dependencies as arguments to the initialisation, rather than just hoping they are defined globally. For example:
class A1(object):
def __init__(self, inputfile):
self.inp = Input(inputfile)
self.board = Board(self.inp.lines[0])
def rotate(self, rotation):
self.current_face = self.board.positions[(self.board.positions.index(self.current_face) + rotation) % 4]
Now in both your main and test files you can instantiate A1 directly by passing the input file.
This is just an example of course; you might want to instantiate the Board object outside the class and pass it in directly. Either way is fine, the important part is that you're passing in any dependencies.
from math import pi
class sphere(object):
def __init__(self,radius):
self.radius = radius
def get_radius(self):
return radius
def surfaceArea(self):
return 4*pi*radius**2
def volume(self):
return (4//3)*pi*radius**3
radius = input("Please enter your radius:")
print sphere.get_radius()
print sphere.surfaceArea()
print sphere.volume()
i need to write the program that prompts the user for a radius then uses your sphere class to output the surface area and volume of a sphere. and I get a type error unbound method get_Radius() must be called with sphere instance as first argument(got nothing instead). Any way to solve this problemo?
You have never created an object from class sphere. Instead of calling sphere.get_radius(), you need to first initiate an object from that class, then call the method on that object.
a = sphere(radius) # initiate an object of class sphere called a
a.get_radius() # call method on the object a.
you need to create a new object and assign redius variable
You need also to use self.redius inside the class.
Check the code below for the above mentioned-comments
from math import pi
class sphere(object):
def __init__(self,radius):
self.radius = radius
def get_radius(self):
return self.radius
def surfaceArea(self):
return 4*pi*self.radius**2
def volume(self):
return (4//3)*pi*self.radius**3
radius = input("Please enter your radius:")
s= sphere(radius)
print s.get_radius()
print s.surfaceArea()
print s.volume()
Here is the function (it's in a file, "worldmodel.py"):
def add_entity(world, entity):
pt = entities.get_position(entity)
if within_bounds(world, pt):
old_entity = occ_grid.get_cell(world.occupancy, pt)
if old_entity != None:
entities.clear_pending_actions(old_entity)
occ_grid.set_cell(world.occupancy, pt, entity)
world.entities.append(entity)
And here is the class in a file named, "occ_grid.py":
class Grid:
def __init__(self, width, height, occupancy_value):
self.width = width
self.height = height
self.cells = []
# initialize grid to all specified occupancy value
for row in range(0, self.height):
self.cells.append([])
for col in range(0, self.width):
self.cells[row].append(occupancy_value)
def set_cell(self, point, value):
self.cells[point.y][point.x] = value
My question is, how would I rewrite the line of code in "def add_entity" that refers to "set_cell"? (Now that I've made set_cell a method of the class Grid) NOTE: Before I made set_cell part of the grid class, it was a function outside of the class (but still in the same file as the class) Thanks!
You'll need to import occ_grid in your worldmodel.py, then instantiate a Grid object and call that objects set_cell()-method. The add_entity needs to get the Grid-object as its parameter unless it can safely instantiate new ones at will.
Here's a naive example which does not work but demonstrates what I mean:
import occ_grid
g = occ_grid.Grid(your_width, your_height, occupancy)
def add_entity(world, entity, grid):
pt = entities.get_position(entity)
if within_bounds(world, pt):
old_entity = grid.get_cell(world.occupancy, pt)
if old_entity != None:
entities.clear_pending_actions(old_entity)
grid.set_cell(world.occupancy, pt, entity)
world.entities.append(entity)
add_entity(world, entity, g)
Unless you make the set_cell function a static method of the Grid class, you're going to need and instance of Grid.
from occ_grid import Grid
I am going to make an assumption here, and say that your want your grid to be part of the world? Either way, this is an example of instantiating that class.
class World:
grid = Grid()
def add_entity(world, entity):
# All that other stuff.
world.grid.set_cell(pt, entity)
There are two issues here, (1) calling functions across modules and (2) calling methods of classes.
It seems you can already do (1).
The trick is that although methods are defined as
def methodName(self, ...)
They are called as
object.methodName(...)
And object implicitly becomes the "self" Parameter. Here is an example:
import occ_grid # Import the module (file) that contains Grid.
.
.
world.occupancy = occ_grid.Grid() # Create an instance of Grid.
.
.
def add_entity(world, entity):
pt = entities.get_position(entity)
.
.
world.occupancy.set_cell(pt, entity)
In this example, grid is a global variable, which is probably not a good design. I guess it should be a property of world, but that's only a guess.
pI am working on a bit of code that does nothing important, but one of the things I am trying to make it do is call a function from another class, and the class name is pulled out of a list and put into a variable. Mind you I have literally just learned python over the last 2 weeks, and barely know my way around how to program.
What I believe that this should do is when getattr() is called, it will pass the attribute 'run_question' that is contained in the respective class with the same name as what is in question_type, and then pass it onto 'running_question'. I know there are probably better ways to do what I am attempting, but I want to know why this method doesn't work how I think it should.
#! /usr/bin/python
rom random import randrange
class QuestionRunner(object):
def __init__(self):
##initialize score to zero
self.score = 0
##initialize class with the types of questions
self.questiontypes = ['Addition', 'Subtraction', 'Division', 'Multiplication']
##randomly selects question type from self.questiontypes list
def random_type(self):
type = self.questiontypes[randrange(0, 4)]
return type
##question function runner, runs question function from self
def run_questions(self):
try:
question_type = self.random_type()
running_question = getattr(question_type, 'run_question' )
except AttributeError:
print question_type
print "Attribute error:Attribute not found"
else: running_question()
class Question(object):
pass
class Multiplication(Question):
def run_question(self):
print "*"
class Division(Question):
def run_question(self):
print "/"
class Subtraction(Question):
def run_question(self):
print "-"
class Addition(Question):
def run_question(self):
print "+"
test = QuestionRunner()
test.run_questions()
This outputs:
[david#leonid mathtest] :( $ python mathtest.py
Division
Attribute error:Attribute not found
[david#leonid mathtest] :) $
Which indicates that I am not getting the run_question attribute as I expect.
I should note that when I put the functions into the QuestionRunner class in the following way, everything works as expected. The main reason I am using classes where it really isn't needed it to actually get a good grasp of how to make them do what I want.
#! /usr/bin/python
from random import randrange
class QuestionRunner(object):
def __init__(self):
##initialize score to zero
self.score = 0
##initialize class with the types of questions
self.questiontypes = ['addition', 'subtraction', 'division', 'multiplication']
##randomly selects question type from self.questiontypes list
def random_type(self):
type = self.questiontypes[randrange(0, 4)]
return type
##question function runner, runs question function from self
def run_questions(self):
try:
question_type = self.random_type()
running_question = getattr(self, question_type)
except AttributeError:
exit(1)
else: running_question()
def multiplication(self):
print "*"
def division(self):
print "/"
def addition(self):
print "+"
def subtraction(self):
print "-"
test = QuestionRunner()
test.run_questions()
Any help on why this isn't working would be great, and I appreciate it greatly.
Any help on why this isn't working would be great, and I appreciate it greatly.
Ah, I have found out the missing concept that was causing my logic to be faulty. I assumed that I could pass the name of an object to getattr, when in reality I have to pass the object itself.