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
Related
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
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 3 years ago.
Improve this question
Suppose I have the following:
class Product
def __init__(self, name="Pepsi"):
self.name = name
self.daily_sales = []
And the daily_sales object is something like this:
{
"date": 2019-01-01,
"price": 1.99,
"revenue: 283.01
}
And the daily_sales in the Product class will just have a bunch of those sales_objects. My questions is, when should something like a dictionary be converted into a separated class? When does it make sense to, and when does it not make sense to? For example:
ProductDailySale:
def __init__(self, product_id):
self.product_id;
self.date;
self.price;
self.revenue;
My guidance would be to almost never use dicts as data structures with fixed layout.
Instead, use classes. A convenient way to define simple data classes is dataclasses or, in older versions of Python, attrs.
I've found two major advantages to this over using dicts, especially when used with pytype and static code analysis:
It is possible to annotate fields with type signatures (and get static type checking).
Misspelled field names are caught at build time instead of causing failures (sometimes silent — think dict.get() returning None) at run time.
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.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm probably missing something obvious here. With the following code:
class Thing():
def __init__(self, name):
self.name = name
that = Thing()
I get the error 'init needs two arguments'. I thought 'self' was one of the arguments and when I try to instantiate the object by putting the name inside the parentheses I get other errors.
Yes, your __init__ takes two arguments: self, and name. When you call Thing(), self is passed implicitly, but you still need to pass the second one explicitly, like Thing("name"). If you're still getting an error when doing that, that's a different story. You should post that error as well.
(And I doubt the error says "init needs two arguments". It would have been more helpful to include the actual error message...)