When do I actually use classes [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I've been coding for a few months now making simple scripts and a few bigger projects but I have never been able to wrap my head around when to actually use classes. It may be that my programs are to small to benefit from them but I just don't understand. Whenever I look up videos about it there is always the same kind of examples. When you have for example a student and you want to store information about it. But I don't understand how this could be implemented in a program. Can someone give an example on when it's useful to use a class and why it is better than not.
Example of student class:
class Student():
def __init__(self, name, grade, gender):
self.name = name
self.grade = grade
self.gender = gender
John = Student("John", "A", "Man")

Classes don't appeal when you are coding small programs. But say you are working on a game using the Pygame module, Classes would come in handy. For example, creating an in-game character using Class definitely makes life easier, as it packs all the information and properties into it. On the contrary, making changes to a game programmed using procedure-oriented code would be extremely hard and annoying. Not to mention the length of the code, you also have to clearly state every possible outcome and event. In short, Class is a beneficial means exclusively available to Object-Oriented-Programming, which is why it is a high-level programming language. Class may not be necessary in many cases, but is still an excellent tool to make your code shorter and easier to read and amend.

Yes. I am very mush interested in classes and objects. And I can tell you use of classes and objects would really help you so much and reduce the lines of codes.
First of all, you should know where to use objects. Suppose, we have to create a game, then definitely we will have some objects in it (these are images that we perceive), but in addition to it there are more properties of an object, like on canvas, its x and y coordinates which change over time, when the object moves. And also, image of that object is itself a property of it.
For example, in Super Mario, you would see Mario as the main character and it is an object in terms of programming. Mario is an object with various properties and methods. What properties and methods? On the canvas (for drawing the image), it has x & y coordinates as I said earlier and in addition to this it has an image, width and height of the image, the methods (functions) like move right, move left, jump etc.
In short, you can say an object as a collection of properties (variables) and methods(functions).
Objects really help in organising all the codes. And more than that, classes help. Classes are templates for creating objects. See, in Super Mario, there are many enemies (I don't know what comes the first time brown one) and turtles and many others. You can notice that all of them have the same image(appearance), properties (size and shape), methods(movements) etc. All of them behave the same way.
So how to create many enemies of one type... Do we copy and paste the codes of object and change their properties (their coordinates are different in the game)? There we use classes... We define the properties and methods of objects that we want, by using variables and then pass different values to the class and create hundreds of objects of the same type.

Related

python, class renaming vs inheriting [duplicate]

This question already has answers here:
How to set class names dynamically?
(3 answers)
Closed 5 years ago.
Would it be correct to say that if some python class is well written,
then
class Subclass(BaseClass):
pass
Should be sufficient to create a well behaved class with similar behavior to that of BaseClass?
(I am writing similar and not identical because for example)
SubClass.name or BaseClass.qualname would not be the same as their counterparts in BaseClass and this would possibly (probably) also extend to str and repr and possibly other metadata.
Would It make sense to use such "empty" inheritance to do class renaming for better semantics e.g. would you inherit collections.Countr to call it GuestsCount if you want to Count how many Adults / Children / Babies will be attending some event? or call it a "Polinomial" and use the count values to represent coefficients of some class that would represent variables to some power ( i.e. X^2 or Y^3 ) and so on ?
EDIT:
I don't see how my Q is even related to dynamic renaming of class in any way AS IS.
I am talking about inheritance v.s. aliasing (or possibly just instantiating) but not about renaming an existing class dynamically nor about dynamically creating classes and issues related to how to name those dynamically created classes as discussed in the so called duplicate mentioned here :(
Although it is not common, I think it does makes sense. I'd refer you to this article by Robert Martin. Especially the last paragraph supports your rationale. Although the article deals with renaming functions, the same arguments could hold for renaming classes.
Additionally, concepts as different as PersonCounter and Polynomial will most likely soon diverge in terms of functionality too, although they start from the same class, so it makes sense to make them different classes.
Note: A closely related, common pattern in python frameworks, is subclasses that have only one class attribute
class GuestCounter(Counter):
datatype=Person
class Polynomial(Counter):
datatype=float
which could be useful if you create factory functions/type checkers/adapter functions for your objects
An additional advantage is that you could add attributes to the SubClass,
while it might not be possible for the BaseClass (dict or list for example).
It might make sense if you actually get better semantics, but in your examples you do not.
Having AdultCounter and ChildCounter suggests that counting adults is somewhat different than counting children, which is false and misleading. Not because they happen to share the same implementation (as explained in the Uncle Bob`s article linked in other answer, that would be fine) but because they are conceptually the same. Counting abstracts over any attributes of the items counted. Counting adults, children, sheep or a mix of them, it is all the same.
adults = AdultCounter({ev: ev.num_adults() for ev in events})
children = ChildCounter({ev: ev.num_children() for ev in events})
The ocasional reader would wonder what do these counters do that a bare Counter does not. After They would have to look at the definitions to find out the answer: nothing. So what's the point? The part that is actually different, the filtering, is done outside the counters.
And for polyomies, a Counter does not look like a good abstraction. Why would mypoly.most_common() return the term with the highest coefficient? Why does poly1 + poly2 work while 2 * poly does not and poly1 - poly2 is buggy?

What does abstraction mean in programming?

I'm learning python and I'm not sure of understanding the following statement : "The function (including its name) can capture our mental chunking, or abstraction, of the problem."
It's the part that is in bold that I don't understand the meaning in terms of programming. The quote comes from http://www.openbookproject.net/thinkcs/python/english3e/functions.html
How to think like a computer scientist, 3 edition.
Thank you !
Abstraction is a core concept in all of computer science. Without abstraction, we would still be programming in machine code or worse not have computers in the first place. So IMHO that's a really good question.
What is abstraction
Abstracting something means to give names to things, so that the name captures the core of what a function or a whole program does.
One example is given in the book you reference, where it says
Suppose we’re working with turtles, and a common operation we need is
to draw squares. “Draw a square” is an abstraction, or a mental chunk,
of a number of smaller steps. So let’s write a function to capture the
pattern of this “building block”:
Forget about the turtles for a moment and just think of drawing a square. If I tell you to draw a square (on paper), you immediately know what to do:
draw a square => draw a rectangle with all sides of the same length.
You can do this without further questions because you know by heart what a square is, without me telling you step by step. Here, the word square is the abstraction of "draw a rectangle with all sides of the same length".
Abstractions run deep
But wait, how do you know what a rectangle is? Well, that's another abstraction for the following:
rectangle => draw two lines parallel to each other, of the same length, and then add another two parallel lines perpendicular to the other two lines, again of the same length but possibly of different length than the first two.
Of course it goes on and on - lines, parallel, perpendicular, connecting are all abstractions of well-known concepts.
Now, imagine each time you want a rectangle or a square to be drawn you have to give the full definition of a rectangle, or explain lines, parallel lines, perpendicular lines and connecting lines -- it would take far too long to do so.
The real power of abstraction
That's the first power of abstractions: they make talking and getting things done much easier.
The second power of abstractions comes from the nice property of composability: once you have defined abstractions, you can compose two or more abstractions to form a new, larger abstraction: say you are tired of drawing squares, but you really want to draw a house. Assume we have already defined the triangle, so then we can define:
house => draw a square with a triangle on top of it
Next, you want a village:
village => draw multiple houses next to each other
Oh wait, we want a city -- and we have a new concept street:
city => draw many villages close to each other, fill empty spaces with more houses, but leave room for streets
street => (some definition of street)
and so on...
How does this all apply to programmming?
If in the course of planning your program (a process known as analysis and design), you find good abstractions to the problem you are trying to solve, your programs become shorter, hence easier to write and - maybe more importantly - easier to read. The way to do this is to try and grasp the major concepts that define your problems -- as in the (simplified) example of drawing a house, this was squares and triangles, to draw a village it was houses.
In programming, we define abstractions as functions (and some other constructs like classes and modules, but let's focus on functions for now). A function essentially names a set of single statements, so a function essentially is an abstraction -- see the examples in your book for details.
The beauty of it all
In programming, abstractions can make or break productivity. That's why often times, commonly used functions are collected into libraries which can be reused by others. This means you don't have to worry about the details, you only need to understand how to use the ready-made abstractions. Obviously that should make things easier for you, so you can work faster and thus be more productive:
Example:
Imagine there is a graphics library called "nicepic" that contains pre-defined functions for all abstractions discussed above: rectangles, squares, triangles, house, village.
Say you want to create a program based on the above abstractions that paints a nice picture of a house, all you have to write is this:
import nicepic
draw_house()
So that's just two lines of code to get something much more elaborate. Isn't that just wonderful?
A great way to understand abstraction is through abstract classes.
Say we are writing a program which models a house. The house is going to have several different rooms, which we will represent as objects. We define a class for a Bathroom, Kitchen, Living Room, Dining Room, etc.
However, all of these are Rooms, and thus share several properties (# of doors/windows, square feet, etc.) BUT, a Room can never exist on it's own...it's always going to be some type of room.
It then makes sense to create an abstract class called Room, which will contain the properties all rooms share, and then have the classes of Kitchen, Living Room, etc, inherit the abstract class Room.
The concept of a room is abstract and only exists in our head, because any room that actually exists isn't just a room; it's a bedroom or a living room or a classroom.
We want our code to thus represent our "mental chunking". It makes everything a lot neater and easier to deal with.
As defined on wikipedia: Abstraction_(computer_science)
Abstraction tries to factor out details from a common pattern so that
programmers can work close to the level of human thought, leaving out
details which matter in practice, but are not exigent to the problem being
solved.
Basically it is removing the details of the problem. For example, to draw a square requires several steps, but I just want a function that draws a square.
Let's say you write a function which receives a bunch of text as parameter, then reads credentials in a config file, then connects to a SMTP server using those credentials and sends a mail using that text.
The function should be named sendMail(text), not parseTextReadCredentialsInFileConnectToSmtpThenSend(text) because it is more easy to represent what it does this way, to yourself and when presenting the API to coworkers or users... even though the 2nd name is more accurate, the first is a better abstraction.
In a simple sentence, I can say: The essence of abstraction is to extract essential properties while omitting inessential details. But why should we omit inessential details? The key motivator is preventing the risk of change.
The best way to to describe something is to use examples:
A function is nothing more than a series of commands to get stuff done. Basically you can organize a chunk of code that does a single thing. That single thing can get re-used over and over and over through your program.
Now that your function does this thing, you should name it so that it's instantly identifiable as to what it does. Once you have named it you can re-use it all over the place by simply calling it's name.
def bark():
print "woof!"
Then to use that function you can just do something like:
bark();
What happens if we wanted this to bark 4 times? Well you could write bark(); 4 times.
bark();
bark();
bark();
bark();
Or you could modify your function to accept some type of input, to change how it works.
def bark(times):
i=0
while i < times:
i = i + 1
print "woof"
Then we could just call it once:
bark(4);
When we start talking about Object Oriented Programming (OOP) abstraction means something different. You'll discover that part later :)
Abstraction: is a very important concept both in hardware and software.
Importance: We the human can not remember all the things all the times. For example, if your friend speaks 30 random numbers quickly and asks you to add them all, it won't be possible for you. Reason? You might not be able to keep all those numbers in mind. You might write those numbers on a paper even then you will be adding right most digits one by one ignoring the left digits at one time and then ignoring the right most digits at the other time having added the right most ones.
It shows that at one time we the human can focus at some particular issue while ignoring those which are already solved and moving focus towards what are left to be solved.
Ignoring less important thing and focusing the most important (for the time being and in particular context) is called Abstraction
Here is how abstraction works in programming.
Below is the world's famous hello world program in C language:
//C hello world example hello.c
#include <stdio.h>
int main()
{
printf("Hello world\n");
return 0;
}
This is the simplest and usually the first computer program a programmer writes. When you compile and run this program on command prompt, the output may appear like this:
Here are the serious questions
Computer only understands the binary code how was it able to run your English like code? You may say that you compiled the code to binary using compiler. Did you write compiler to make your program work? No. You needed not to. You installed GNU C compiler on your Linux system and just used it by giving command:
gcc -o hello hello.c
And it converted your English like C language code to binary code and you could run that code by giving command:
./hello
So, for writing an application in C program, you never need to know how C compiler converts C language code to binary code. So you used GCC compiler as an abstraction.
Did you write code for main() and printf() functions? No. Both are already defined by someone else in C language. When we run a C program, it looks for main() function as starting point of program while printf() function prints output on computer screen and is already defined in stdio.h so we have to include it in program. If both the functions were not already written, we had to write them ourselves just to print two words and computers would be the most boring machines on earth ever. Here again you use abstraction i.e. you don't need to know how printf prints text on monitor and all you need to know is how to give input to printf function so that it shows the desired output.
I did not expand the answer to abstraction of operating system, kernel, firmware and hardware for the sake of simplicity.
Things to remember:
While doing programming, you can use abstraction in a variety of ways to make your program simple and easy.
Example 1: You can use a constant to abstract value of PI 3.14159 in your program because PI is easy to remember than 3.14159 for the rest of program
Example 2: You can write a function which returns square of a given number and then anyone, including you, can use that function by giving it input as parameters and getting a return value from it.
Example 3: In an Object-oriented programming (OOP), like Java, you may define an object which encapsulates data and methods and you can use that object by invoking its methods.
Example 4: Many applications provide you API which you use to interact with that application. When you use API methods, you never need to know how they are implemented. So abstraction is there.
Through all the examples, you can realize the importance of abstraction and how it is implemented in programming. One key thing to remember is that abstraction is contextual i.e. keeps on changing as per context

Call the same method in all objects in Python?

Long story short, I need to find a shortcut to calling the same method in multiple objects which were made from multiple classes.
Now, all of the classes have the same parent class, and even though the method differs bewteen the different classes, I figured the methods be the same name would work. So I though I might just be able to do something like this:
for object in listOfObjects:
object.method()
It hasn't worked. It might very well be a misspelling by me, but I can't find it. I think I could solve it by making a list that only adds the objects I need, but that would require a lot of coding, including changing other classes.
~~ skip to last paragraph for pseudo code accurately describing what I need~~
At this point, I will begin to go more in detail as to what specifically I am doing. I hope that it will better illustrate the scope of my question, and that the answering of my question will be more broadly applicable. The more general usage of this question are above, but this might help answer the question. Please be aware that I will change the question once I get an answer to more closely represent what I need done, so that it can apply to a wide variety of problems.
I am working on a gravity simulator. Whereas most simulators make objects which interact with one another and represent full bodies where their center of gravity is the actual attraction point, I am attempting to write a program which will simulate the distribution of gravity across all given points within an object.
As such, each object(not in programming terms, in literal terms) is made up of a bunch of tiny objects (both literally and figuratively). Essentially, what I am trying to do is call the object.gravity() method, which essentially takes into account all of the gravity from all other objects in the simulation and then moves the position of this particular object based on that input.
Now, either due to a syntactical bug (which I kinda doubt) or due to Python's limitations, I am unable to get all of the particles to behave properly all at once. The code snippet I posted before doesn't seem to be working.
tl;dr:
As such, I am wondering if there is a way (save adding all objects to a list and then iterating through it) to simply call the .gravity() method on every object that has the method. basically, even though this is sort of list format, this is what I want to do:
for ALL_OBJECTS:
if OBJECT has .gravity():
OBJECT.gravity()
You want the hasattr() function here:
for obj in all_objects:
if hasattr(obj, 'gravity'):
obj.gravity()
or, if the gravity method is defined by a specific parent class, you can test for that too:
for obj in all_objects:
if isinstance(obj, Planet):
obj.gravity()
Can also do ... better pythonic way to do it
for obj in all_objects:
try:
obj.gravity()
except AttributeError:
pass
Using getattr while set default option of getattr to lambda: None.
for obj in all_objects:
getattr(obj, 'gravity', lambda: None)()

Easy Problems for Children to Solve in Python [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm going to be teaching some year 9 and 10 students Python soon and thought it would be cool to do some Project Euler type challenges with them. The first problem seems doable by them, but I think some of the others may be a bit over their head, or not require enough programming.
If anyone has a place to find some easy programming problems, or can think of any, can they please let me know.
edit: By year 9 and 10 I mean that they have been in school for 9 or 10 years. So about 13, 14, and 15 type age. Sorry for the confusion!
Oh I remember something I was taught in school! My IT teacher created a class in python which attributes created a mathematical sequence. The goal was to guess the formula behind this sequence using only python. Obviously, you couldn't look at the file with class, only import it in python. Maybe there's more math than programming here, but to solve this, students will have to learn how variables, namespaces (to find the variables), loops (to print those variables), and classes (which store those variables) work in python and this is more or less everything you need to know at first, in my opinion.
Ah, good times. We also used to play "hide and seek" in shell on IT lessons: the teacher would hide a file somewhere and leave some clues scattered around, and we had to find that file using text environment on linux :)
Get the right number :
The program chooses a random value betwen 1 an 100 then you have to guess.
It tells you if you are above or below.
My first scholar contact with programming really left a mark on me ;) The teacher provided us with a gui containing a sort of 2-d checkered board (let's pretend it was 20x20 cells). One of the cells contained a 'robot' and the programming interface basically exposed 3 methods: move forward, turn left, and check if the cell directly in front of the robot is a wall or open space. The game was then to 'program the robot' (teaching basic logic and loop constructs) to do all sorts of tasks like pass through every cell in the board. Later on, methods were added to the interface (to the original 3 methods) and 'objects' (not OOP, but .. other states the cells could occupy than just wall or empty) were added to the game. In the end the goals were for example for the robot to 'pick up' car parts and bring them to a 'car factory'. It was very nice IMHO to view programming as a game with 'scores' (least amount of cells required to achieve objective in this case) and I really promote Gamification http://en.wikipedia.org/wiki/Gamification in any school environment.
Cheers
Not sure how long you have to teach this, but Udacity's cs101 class has some pretty cool problems and starts from a pretty simple level. The course is free, and you may find some of the problems useful stand alone if you don't have time for the whole thing.
Finally if you run out of ideas for meaningful projects that are easy enough / quick enough in Python or decide to find something easier for part of the class then consider using Scratch, this is a fun visual programming language from MIT which allows you to use the constructs such as variables, loops, conditions etc. without worrying about syntax. This makes it nice and easy to create basic games / animations.

How to organise the structure of a 3D game?

This is a bit of a vague question but bear with me. I am in the process of writing a game using Python/Pyglet and openGL. I currently have it structured so that there is an object called 'world', in this are other objects with other objects inside them etc. I did it this way because for instance one part of the game is a platform with other objects on it, and when I tilt the platform I want the objects on it to tilt with it. So I do platform.draw() which calls glRotate, glTranslate, then draw each of the objects saving the modelview matrix inbetween, this way all the objects on the platform move together.
The first question is, is this a sensible way to organise things or should I be using some other method?
I don't have a camera class, currently I am just translating the whole world or parts of it to give the illusion of movement. However, in the future I want to be able to switch viewpoints between objects, so for instance switch from looking down onto the world from above to a 1st person view from one of the objects in the world. So the second question is what is the best way to structure my program so that this will be achievable in the future?
Not probably a full answer, but i think a full one would take a whole book...
What you are doing with your representation of the world in a hierarchy is very similar to what is usually known as "scene-graph", and it is a good idea in many cases. A good example of a library to do precisly this is Open Scene Graph.
About "translating the world", unless you are really transforming all the vertices every time, it is also perfectly fine. It is just a matter of relative point of view and what your really have is the same that a camera matrix. You can see the transformation as placing the camera in the world, or as moving the world in front of the camera.
You could put the logic into a seperate module / into seperate classes/functions.
In my 2D-Game I have a GameLogic class which simplifies registering it's methods for certain events or scheduling them (and unregistering+unscheduling them), and I created a #state_wrapper decorator which injects a simple new-style object as state-storage for that method. If you do it like that you don't have to pass the pointer to all your world objects, only the event-methods have to get access to your objects.
But I wouldn't claim that this is the best solution ;)

Categories

Resources