Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with Classes
#1
Hello!i am 16 years old and my teacher at school decided to teach us Python.At the beginning Python was easy until the moment classes and inheritance showed up!
i have an exercise here and i would like to help me (if you can of course).There are some points where i have queries.
Here is my exercise:
"You decided to create a game called "DangerousShapes".Τhe player moves on a (11,29)grid where random shapes appear and block his path.Those shapes are spheres and triangles.For triangles we know width,lengh and height and for spheres their radius.The triangles give penalty 5 moves to the player and the spheres give penalty of 3 moves.
Create:
1.Classes and subclasses where you must write all the necessary information like characteristics of shapes and their coordinates.
2.Create a list to save 12 random shapes
3.Every shape must have coordinates inside the grid and the coordinates must be created in random way for each shape and check if there is another shape in that spot.
4.Use print to check if there are 12 shapes in the grid and show their coordinates"

That is my exercise.
when i return home (i am at school now) i will show you what i have done -but i think its wrong at some points- and please do not yell at me.. Big Grin

Basically i am confused with 2 and 3.
but i will show you and number 1 question to help me correct it (if you can of course)
Reply
#2
You would start with 2 classes, one for triangles and one for spheres. You can create as many instances, (unique shapes), as you want.

Quote:2.Create a list to save 12 random shapes
Randomly choose from a triangle or sphere. Based upon the shape, randomly choose the parameters to pass to the appropriate class i.e. for a sphere you would only choose a radius within some minimum and maximum values. When you have this much coded, post back and we can help you further.
Reply
#3
(Feb-14-2019, 08:06 PM)woooee Wrote: You would start with 2 classes, one for triangles and one for spheres. You can create as many instances, (unique shapes), as you want.

Quote:2.Create a list to save 12 random shapes
Randomly choose from a triangle or sphere. Based upon the shape, randomly choose the parameters to pass to the appropriate class i.e. for a sphere you would only choose a radius within some minimum and maximum values. When you have this much coded, post back and we can help you further.

Thanks for the tips! (but i need 3 claases)
Anyway, i decided not to solve it since i know that my classes are wrong and basically i dont understand what i am doing.
So,i am sorry for this mess!
i was crying all night yesterday since i couldn't solve it and i decided to quit.
Reply
#4
(Feb-15-2019, 08:05 AM)Lonewolf Wrote: Thanks for the tips! (but i need 3 claases)
Anyway, i decided not to solve it since i know that my classes are wrong and basically i dont understand what i am doing.
So,i am sorry for this mess!
i was crying all night yesterday since i couldn't solve it and i decided to quit.

It may sound complicated but it's not. If you step back and look at it with fresh mind you will see. Don't worry you don't understand everything - that's an excellent opportunity to learn.
For start:
you need at least three classes - Grid, Triangle, Sphere.
Because Triangle and Sphere would have common attributes, you can have a parent class Shape (so 4 classes in total) and both Triangle and Sphere would inherit from it (i.e. Shape would have common attributes like x, y and penalty, while Triangle and Sphere would add their specific attributes like side1, side2, side3 or radius.
Grid would have a method that will randomly populate 12 positions with a shape - either triangle or sphere.

We are not going to give you ready solution, but we will help you along the way.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
i don't think i need a grid class since teacher told us not to use one and the set of coordinates should be saved in each class.

well, i have 2 days to solve this.This momment i can't.i don't know what i am doing.
for example:
the 3 classes i need are:

class Shape:
    def __init__(self,x,y,penalty):
        self.x=x
        self.y=y
        self.penalty=penalty

class Triangle(Shape):
    def __init__(self,width,height,lengh):

class Sphere(Shape):
    def __int__(self,radius):
i know that triangle and sphere inherit from Shape but i dont know how to write it.it's conusing.
in generall i know that for random i must use randit but that's all.i can use it (i think) if it was one oblject but with two??nope ---teacher told ud to make it easier to fill it with objects of the characteristics example all triangles same height,width,lenght etc and that momment i cried and i told myself to quit
Reply
#6
(Feb-15-2019, 10:06 AM)Lonewolf Wrote: i don't think i need a grid class since teacher told us not to use one and the set of coordinates should be saved in each class.

Yes, you can skip the Grid class, although normally you would use it. If teacher explicitly tells you not to use one, then don't

(Feb-15-2019, 10:06 AM)Lonewolf Wrote: i know that triangle and sphere inherit from Shape but i dont know how to write it.it's conusing.

Fix your classes, before you do the random/grid part. For the inheritance part - take a look at this https://www.pythonforbeginners.com/super...r-function

One problem with your code as it is now - you need to pass all the necessary information when instantiate triangle or sphere (i.e. instance of the class). I mean all the information - that is, not only width, height, length or radius, but also x, y, and penalty, but also the information for the parent class - x, y and penalty. Then you will use x, y, and penalty to initialize the parent class.

(Feb-15-2019, 10:06 AM)Lonewolf Wrote: teacher told ud to make it easier to fill it with objects of the characteristics example all triangles same height,width,lenght etc
That means you can define default values for these properties.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
(Feb-15-2019, 10:39 AM)buran Wrote: Fix your classes, before you do the random/grid part. For the inheritance part - take a look at this https://www.pythonforbeginners.com/super...r-function

One problem with your code as it is now - you need to pass all the necessary information when instantiate triangle or sphere (i.e. instance of the class). I mean all the information - that is, not only width, height, length or radius, but also x, y, and penalty, but also the information for the parent class - x, y and penalty. Then you will use x, y, and penalty to initialize the parent class.
class Shape:
    def__init__(self,x,y,penalty):
        self.x=x
        self.y=y
        self.penalty=penalty
 
class Triangle(Shape):
    def__init__(self,width,height,lengh):
    super().__init__(x,y,penalty)
 
class Sphere(Shape):
    def__int__(self,radius):
    super().__init__(x,y,penalty)
that's what you mean??
Reply
#8
More or less - yes.
You need to pass x, y and penalty in the __init__() of the Triangle and Sphere class. Also you can set default values. And finally - you need a space between def and __init__
class Shape:
    def __init__(self, x, y, penalty):
        self.x=x
        self.y=y
        self.penalty=penalty
  
class Triangle(Shape):
    def __init__(self, x, y, penalty=5, width=1, height=1, length=1):
        super().__init__(x ,y, penalty)
        self.width = width
        self.height = height
        self.length = length
  
class Sphere(Shape):
    def __init__(self, x, y, penalty=3, radius=1):
        super().__init__(x, y, penalty)
        self.radius = radius
        
triangle = Triangle(x=1, y=2) # instanciate triangle at position x=1, y=2
print('position x, y => (x={}, y={})'.format(triangle.x, triangle.y))
print('penalty => {}'.format(triangle.penalty))
print('height => {}'.format(triangle.height))
Output:
position x, y => (x=1, y=2) penalty => 5 height => 1 >>>
Note that using super() is the better way to do so and I hope your teacher showed it to you. Because there is only one parent class, same can be done like this
class Triangle(Shape):
    def __init__(self, x, y, penalty=5, width=1, height=1, length=1):
        Shape.__init__(self, x ,y, penalty) # note the difference how we initialize the parent class
        self.width = width
        self.height = height
        self.length = length
But as I said using super() is better.

Now, how would you create the grid and generate random positions?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#9
can i ask something?
For question 1 my exercise says : Set in all classes the appropriate methods to retrieve and store a new value for each class attribute.
How you do that?

as for the grid -it's not neseccary though -i could use something like that:
    grid = []
# row
for row in range(11):
    grid.append([])
#  column
for column in range(25):
    grid.append([])
Reply
#10
(Feb-15-2019, 04:55 PM)Lonewolf Wrote: can i ask something?
For question 1 my exercise says : Set in all classes the appropriate methods to retrieve and store a new value for each class attribute.
How you do that?

Short answer: in python you don't use setter and getters unless you really have to. And in this case you definitely don't need them.

Long answer: In some programming languages you are required to use methods to retrieve (getter) and to store (setter) for each class attribute. In python you don't unless you have to. Sorry to say that, but actually creating getters and setters for each attribute is considered bad programming in python. Probably your teacher comes from Java or other language that requires them and is following the same pattern with python. Now I don't know if you would want to tell them this but it's true.

Let's create yet another class - Circle, just to use as an example in the following explanations:

class Circle:
    def __init__(self, radius):
        self.radius = radius

# create circle with radius=2
circle = Circle(radius=2)

# print the circle radius
print('radius = {}'.format(circle.radius)) # i.e. here you retrieve the value of attribute radius

# change (set) new radius
circle.radius = 5 # here you set the value

# print the circle radius
print('radius = {}'.format(circle.radius)) # i.e. here you retrieve the value of attribute radius
Output:
radius = 2 radius = 5
as you can see you don't need to have special methods to set and retrieve the value of attribute radius.

What your teacher wants is something like this

class Circle:
    def __init__(self, radius):
        self._radius = radius # we use _radius as an internal "storage" for the value of attribute radius

    def get_radius(self):
        return self._radius

    def set_radius(self, value):
        self._radius = value 

# create circle with radius=2
circle = Circle(radius=3)

# print the circle radius
print('radius = {}'.format(circle.get_radius())) # i.e. here you retrieve the value of attribute radius

# change (set) new radius
circle.set_radius(10) # here you set the value

# print the circle radius
print('radius = {}'.format(circle.get_radius())) # i.e. here you retrieve the value of attribute radius

# However you can still do following and change the radius without using the set method
circle._radius = 5
# print the circle radius
print('radius = {}'.format(circle.get_radius())) # i.e. here you retrieve the value of attribute radius

As I said, this is bad code, so don't do it
. From the last example you can see that you don't need the set_radius method. You can just change the self._radius.

Now what you will do in python if you have to? It may be a bit advanced for you, so don't worry if you don't understand it. The take away is - you do use setters and/or getters only when you really need them.

let's say you want to add another attribute to Circle class - diameter. you know that diameter = radius*2. That means that you need radius and diameter to be always in sync. what you will do?

Also if you want to calculate the area of circle and define attribute area? You need to calculate using circle radius and you should not be able to set the area...

class Circle:
    def __init__(self, radius):
        self.radius = radius

    # this is the "getter" for diameter
    @property
    def diameter(self):
        return self.radius * 2 # return diameter calculated from radius

    #this is the "setter" for diameter
    @diameter.setter
    def diameter(self, value):
        self.radius = value / 2 # here we use setter so that we can change the value of self.radius

    @property
    def area(self):
        return 3.14 * self.radius **2

# create circle with radius=2
circle = Circle(radius=3)

# print the circle radius
print('radius = {}'.format(circle.radius)) # i.e. here you retrieve the value of attribute radius
# print the circle diameter
print('diameter = {}'.format(circle.diameter)) # i.e. here you retrieve the value of attribute diameter

# change (set) new diameter
circle.diameter = 10 # here you set the value
# print the circle radius
print('radius = {}'.format(circle.radius)) # i.e. here you retrieve the value of attribute radius
# print the circle diameter
print('diameter = {}'.format(circle.diameter)) # i.e. here you retrieve the value of attribute diameter

print('area = {}'.format(circle.area)) # i.e. here you retrieve the value of attribute area

circle.area = 100 # here you will get error
Output:
radius = 3 diameter = 6 radius = 5.0 diameter = 10.0 area = 78.5
and then you get this error
Error:
Traceback (most recent call last): File ****, line 36, in <module> circle.area = 100 # here you will get error AttributeError: can't set attribute
As I said - probably you don't understand everything but I just wanted to show how you would properly do it in python.

As to the grid - it's not very clear from your assignment if you need just a list that will hold just 12 shapes, or a grid that will resemble 11x29 grid, i.e. list of lists. In any case it's not what you did. print your grid and see what you egt. Is it really what you want?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020