dil_bert Posted May 21, 2019 Share Posted May 21, 2019 hello dear experts, good evening, I was watching a tutorial on class, static and instance methods and they'res 3 things I can't seem to wrap my head around: When should I use either of the 3 methods? What does the "__repr__" do?The example the tutor used does for the code and the project. : class Pizza: def __init__(self, ingredients): self.ingredients = ingredients def __repr__(self): return f"Pizza({self.ingredients})" @classmethod def margherita(cls): return cls(['cheese', "tomatoes"]) Pizza(["Pepperoni", "Pinnaple", "ham", "mushrooms"]) How come at the end he was able to fit 3 arguments inside 1 parameter in the __init__ method? ["Pepperoni", "Pinnaple", "ham", "ushrooms"] is a single item, a list in this case, being passed onto ingredients. why he used classmethods and no static methods or instance methods well - i really look forward to hear rm you Quote Link to comment https://forums.phpfreaks.com/topic/308739-class-static-and-instance-methods-in-python-how-to-use/ Share on other sites More sharing options...
gizmola Posted May 24, 2019 Share Posted May 24, 2019 Quote What does the "__repr__" do? __repr__ is a special class function named as a shortend version of "representation", that is essentially a to_string equivalent. It gets called when you try to use an object as if it was a string as well as in some other situations where you want a representation of the object rather than the object itself. For example, if you execute: my_pizza = Pizza(["onions", "peppers"]) print(my_pizza) WIthout a __repr__ or __str__ class function, Python will just print information about the object. With the __repr__ by convention, the goal is to return an unambiguous representation of the object in a way that the result would be valid Python which could be run again as Python code. This is why the __repr__ is returning Quote Pizza(["Pepperoni", "Pineapple", "ham", "mushrooms"]) Because that is how the object was created. Quote How come at the end he was able to fit 3 arguments inside 1 parameter in the __init__ method? There are not 3 arguments. There is one argument to the constructor (not including the implicit self), but that argument can be any valid Python type. In the example, the parameter being passed is a list. Quote why he used classmethods and no static methods or instance methods I would assume to help teach you about the repr magic method. Other types of methods whether static or instance methods have to be explicitly called. Magic methods are called auto "magically" by Python when it's appropriate. Quote Link to comment https://forums.phpfreaks.com/topic/308739-class-static-and-instance-methods-in-python-how-to-use/#findComment-1567049 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.