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 days ago.
Improve this question
How should I initialize multiple class arguments that came as chain and then calculate sum of them?
I've tried many ways but NOTHING
Do you have any idea?
>>> Chain(2.5)(2)(2)(2.5) # sum
9
>>> Chain(3)(1.5)(2)(3) # sum
9.5
In general, you'll want to add a __call__ method to your class so that calling an instance returns a new instance. Your class should also subclass the type matching the result you want.
In this specific case, the new instance could, for example, maintain a running sum of the initial value and all successive arguments.
class Chain(float):
def __call__(self, x):
return Chain(self + x)
Then
>>> Chain(2.5)
2.5
>>> Chain(2.5)(2)
4.5
>>> Chain(2.5)(2)(2)
6.5
>>> Chain(2.5)(2)(2)(2.5)
9.0
Related
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 2 years ago.
Improve this question
Suppose I have two functions
def sum(a, b):
result = a + b
return result
and
def sum(a, b):
return a + b
From the point of view of good programming practices and software engineering, which solution is better? Return a value or assigning a value to a variable and then return? Why?
2nd option is good because it saves space of a variable but at times, we use more variables on purpose for the sake of clarity. We always have to maintain a good balance between clarity and space.
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 2 years ago.
Improve this question
Where are the python operators like +, -, * defined? I am a newbie, so please give a detailed answer to this question.
every Python class has built-in methods (can be recognized by the "__" in the beginning and end of their name) that define their behavior. for example, when using print() on an object, the built-in __str__ function is called, and it is different for every class.
you can override these functions with your own implementations.
here is a class named CarCollection:
class CarCollection():
def __init__(self, car_list):
self.cars_in_collection = car_list
now, say for example you want to add two collections together. using the "+" between two instances of this class will raise TypeError: unsupported operand type(s) for +: 'instance' and 'instance', so in order to add two collections together you need to override the __add__ function:
def __add__(self, other_car_collection):
return self.cars_in_collection + other.cars_in_collection
now when you add two collections together and print the result it will look like this:
first_collection = CarCollection(["subaru", "ferrari"])
second_collection = CarCollection(["fiat", "renault"])
print(second_collection + first_collection)
output: subaru, ferrari, fiat, renault
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 years ago.
Improve this question
I understand the technical definition of python closures: let's make it concrete.
def foo(x):
def bar(y):
print(x+y)
return bar
In this example x will get bound with bar. But what are these things actually good for? ie in the toy example above one could have just as easily written
def bar(x,y):
print(x+y)
I would like to know the best use cases for using closures instead of, for example, adding extra arguments to a function.
I think the most used example of closure is for caching functions with a decorator.
def cache_decorator(f):
cache = {}
def wrapper(*args):
if args not in cache:
cache[args] = f(*args)
return cache[args]
return wrapper
#cache_decorator
def some_function(*args):
...
This way the cache cannot be referenced from anywhere, since you do not want your users to tamper with it.
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 5 years ago.
Improve this question
I am new on Python.
I want to create a function with two vectors inside. I tried like this
def twovectors((velocity1,length1),(velocity2,length2)):
but I have a message error like
SyntaxError: invalid syntax.
Please, need help.
You cannot put tuple in the function definition as a parameter. Check Multiple Function Arguments or 8.6. Function definitions in the Python language reference.
Try something like this this:
def twovectors(vector1, vector2):
velocity1, length1 = vector1
velocity2, length2 = vector2
# Other code...
I used tuple unpacking to expand provided tuple arguments.
You write functions in python in this way :
def twovectors(velocity1, velocity2):
# You can get the length of those vectors after you get inside the function
len1, len2 = len(velocity1), len(velocity2)
// Your code here
return whateveryouwantto
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 7 years ago.
Improve this question
In python, if a person has the following code, will the 2 methods called automatically add? how does this work?
example:
def trip_cost(city,days):
return plane_ride_cost(city) + hotel_cost(days) + rental_car_cost(days)
Will hotel_cost(days) and rental_car_cost(days) both be added together when they are returned to trip_cost(city,days) ??
If the return values of the methods you invoke have a defined + operator they will add up.
If the 3 return numeric types (for example: float, int): yes
But if 2 return numeric and one returns a str: no
The return values may also be instances of objects defined by yourself which may have a defined + operator (which may or may not be compatible with numeric types or with strings)
Each function call [e.g. plane_ride_cost(city)] is evaluated and the results will be added together (in left to right order as +'s have equal precedence) then the overall result returned.