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 4 days ago.
Improve this question
I know, my title is too broad (or not appropriate much?). But, if you can suggest better title, please help me.
I've seen programmers using different styles of coding in their projects, and using different manners when it cames to use functions.
Here is some function that performs certain task (I tried to keep examples shorter):
class Shrek:
...
def action(self):
self.x += self.shift_factor
if self.x + self.gamer_len > self.window_width:
self.x = self.window_width - self.gamer_len
And here is another approach of above code, that action() method splitted into sup-functions/sub-tasks:
class Fiona:
...
#---------- Main function ----------#
def action(self):
self.move_right()
self.keep_player_inside_window()
#------- Secondary functions -------#
def move_right(self):
self.x += self.shift_factor
def keep_player_inside_window(self):
if self.x + self.gamer_len > self.window_width:
self.x = self.window_width - self.gamer_len
I prefer/use second way, and believe second way is better.
So, my questions are:
Which way is better? and according to what/who? Or which one is good practice?
Can we say first way is faster? (although this question sounds silly, please guide me)
Or action() method is small enough that we don't need to split it into smaller functions?, and it's better to use functions for larger tasks?
The answer(s) for my question(s) might be very obvious, but rather than following my assumptions, I'm posting my question here to be sure that I'm writing better code.
Besides, I hope this post will be beneficial for other users as well. thanks!
most of the time you should use two criteria:
is my code readable
am I repeating the same code over and over again.
So if you have a very long function you might want to split it in a few functions. b
But length is not the only criteria for a function to be readable or unreadable. If you were to ask a question about an unwanted behavior in the next code. for me, that don't know the context of what you're doing the next code makes no sense and would have to debug and experiment with the code
def action(self):
self.x += self.shift_factor
if self.x + self.gamer_len > self.window_width:
self.x = self.window_width - self.gamer_len
while tells me exactly what I need to know to start working on your project
def action(self):
self.move_right()
self.keep_player_inside_window()
you can also consider that everybody in your project should know what self.x += self.shift_factor does so there is no right or wrong answers you should know who are you writing code for.
DO NOT REPEAT YOURSELF!
you want to call the function move_rigth() instead of repeating the code of move_right() in the next 3 functions.
def action(self):
self.move_right()
self.keep_player_inside_window()
def action2(self):
self.move_right()
self.move_forward()
def action3(self):
self.move_right()
self.move_backwards()
Related
I have a question regarding the multiprocessing of objects. I'm not sure if just my syntax isn't right or if I'm completely in the wrong direction with this one.
Let's say I have a class with some defined methods:
class Body:
def __init__(self, x,y):
self.x = x
self.y = y
def update(self, other):
self.x += other.y
def update2(self):
self.x += 1
Now I have a routine that creates the objects and loop through them to update them. I use itertools.product (as I want to add a value of every object to another value of one object). 'bodies' is a list of the created objects
class Calc:
def __init__(self, bodies):
self.bodies = bodies
for body,_body in itertools.product(self.bodies,self.bodies):
body.update(_body)
Everything works fine and I get the right results. Now I would like to multiprocess this for loop. I've already done so with another loop in the file but can't get this to work. And after hours of trying I'm to sure what to do. Or if it's a completely wrong approach.
I'm using concurrent.futures and create
self.p = cf.ThreadPoolExecutor(max_workers=multiprocessing.cpu_count())
in the Calc class
A working function I have is:
for result in self.p.map(Body.update2, self.bodies):
pass
My ideas so far have led me to:
for result in self.p.map(lambda body, _body: Body.update(body,_body), self.bodies, self.bodies):
pass
Or some variants of that. I get no error messages but the answers are clearly wrong. The non multiprocess version of map() has the same result. So I guess the bug lies somewhere in a wrong syntax. But yet I get no errors..
I hope I worded my question not that bad. It's my first question here and english is not my native language.
So again: Can't I use the map() function the way I intended to? Is there another function that's more suitable? Or do I have to take another approach to calculating everything "outside" of the objects themself?
Thanks if you have taken the time to read until here. Any help or direction where to look is appreciated.
Have a good day.
Edit:
Ok, I got the map function to work. I wanted to convert this function:
for body,_body in itertools.product(self.bodies,self.bodies):
body.update(_body)
My solution that works well is:
for body in self.bodies:
for result in map(lambda _body:Body.update(body,_body), bodies):
So as I already guessed my use of the lamda function wasn't quite right.
But now I have the problem, if I understand it correct that objects can't be updated in that way in a multi process serialization so I have to rewrite the code a bit.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
def function(x+4):
return (x*5)+3
SyntaxError: invalid syntax
Why is that? i don't get the logic behind it?
(i know that it is a simple question but i couldn't find an answer to it.
i got many unclear feedbacks about my question,i am sorry about that as english is not my first language i couldn't clarify my question in short:
While i was learning about what return does,i compromised the logic with the logic behind f(x)= codomain as def function(x) = return codomain
but as you know there are functions in maths like f(x+2) = 5x+3. I thought maybe i could do the same on def function,the problem was it was giving a syntax error ,and i was curious about the design idea behind it and if there was an alternative solution to implement this in code.Thanks for answers!
This is a rather uncommon syntax you are suggesting and it is simply not part of Python's syntax, or any language that I know.
Although, what you want to do boils down to updating an argument before it is passed to a function. This can be done with a decorator.
def add_four_to_argument(f):
return lambda x: f(x + 4)
#add_four_to_argument
def func(x):
return (x*5)+3
print(func(1)) # 28
Since you asked about the logic behind that design decision, how would you expect that syntax to behave? Note that it is not the same x being shared everywhere. The following are the same:
x = 5
def f(x):
return x
print(f(x)) # Prints 5
x = 5
def f(y):
return y
print(f(x)) # Prints 5
This allows you to scope your variables and not have to debug the confusing shared state that exclusive use of global variables can cause.
Back to your question though, nowhere else in Python does the addition operator cause assignment (barring abuse of dunder methods...don't do that). So, in your hypothetical f(x+4), what happens to the x+4? Is that supposed to be a placeholder for x=x+4, or is that supposed to be assigned to some new variable representing some ethereal notion of "argument 1" for the function?
Let's dive into it a little further. What about the following example:
def f(x+y):
return x
Suddenly things got a whole lot more ambiguous. How do we call this function? Do we use f(1,2)? Do we only pass a single argument f(3) and guess which portion corresponds to x and which corresponds to y? Even if we figure out the semantics for calling such a function, what does the statement x+y actually do? Does it stand for x=x+y? For y=x+y? For arg1=x+y?
By not allowing the behavior you're describing, Python makes your intent clear. To do a thing, you have to tell Python to actually do that thing. From the Zen of Python,
explicit is better than implicit.
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 8 years ago.
Improve this question
Is there a strong reason to use a retval variable vs just returning a calculation?
def add(self, x, y):
return x + y
versus
def add(self, x, y):
retval = x + y
return retval
I feel like I usually see retval (or some other named variable) in code examples but it seems like a (small) waste to me.
In this example it won't make a difference but in longer functions it can be beneficial (for subjective reasons) to have one result or retval variable and only return that value at the end. This can make the code easier to understand (provided it is structured well) by only having one return location.
That being said, it depends on the developer's preferences and in some functions multiple return locations are equally readable.
The only reason to use it is when you want to use the value before you return it. for example, printing it before you return.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to coding Python and I just can't seem to understand what a Def function is! I have looked and read many tutorials on it and I still don't quite understand. Can somebody explain to me what it is, what I use it for, and give me some examples. For the examples please make them easy and understandable for a newb to Python. Thanks!
def isn't a function, it defines a function, and is one of the basic keywords in Python.
For example:
def square(number):
return number * number
print square(3)
Will display:
9
In the above code we can break it down as:
def - Tells python we are declaring a function
square - The name of our function
( - The beginning of our arguments for the function
number - The list of arguments (in this case just one)
) - The end of the list of arguments
: - A token to say the body of the function starts now
The following newline and indent then declare the intentation level for the rest of the function.
It is just as valid (although uncommon) to see:
def square(number): return number * number
In this case, as there is no indentation the entirety of the function (which in this case is just one line) runs until the end of line. This is uncommon in practise and not considered a good coding style.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
i have been trying to get some stats in a text based game i have been making. i tried to return the variable from the function but every time i try to put it in a global variable i get a name error. I have looked up many topics about this but what i found didn't help me much. Here is the code i made to try and fix the game.
def HEALTH():
health =['''
===============''','''
==============''','''
=============''','''
============''','''
===========''','''
==========''','''
=========''','''
========''','''
=======''','''
======''','''
=====''','''
====''','''
===''','''
==''','''
=''','''
x''']
return health
health =HEALTH(health)
print(health[0])
In your function definition HEALTH takes no arguments. Thus, the following line is bound to fail:
health =HEALTH(health)
In fact, this line looks more like you are trying to create a class named HEALTH but it's especially bound to fail because you are using the variable you are defining as an argument to the function health.
Probably what you are trying to do is accept an argument in the function definition:
def HEALTH(health_level):
health=['''...''']]
return health[health_level]
print(HEALTH(0))
We should have some better names for stuff too. Why not call your function something like the following:
def get_health(health_level):
health=['''...''']
return health[health_level]
That way you're not simply using the word "health" over and over again in possibly confusing ways.
Also, I think you've misunderstood a python coding convention. Typically ALL_CAPS names are reserved for CONSTANTS - variables you don't expect uses to change. For example you might have a starter value for health like this:
HEALTH_DEFAULT = 100
class Character(object):
def __init__(self):
self.Health = HEALTH_DEFAULT
class BuffCharacter(Character):
def __init__(self):
self.Health = HEALTH_DEFAULT * 2
in your case, it looks like you're trying to keep an index of graphic printouts of health for a range of values. You probably want more like this:
HEALTH_DISPLAY = ["=" * i for i in range (10, 0, -1)] + ["X"] # easier on the eyes!
def get_health(val):
return HEALTH_DISPLAY[val]