Search code examples
pythonclass

Class initalization in Python - when to use parentheses and default values


class Example:
    def __init__(self, sides, name):
        self.sides = sides 
        self.name = name

Why are the additional attributes below (interior_angles and angle) not defined in the parentheses and then written out in a function?

class Example:
    def __init__(self, sides, name):
        self.sides = sides 
        self.name = name
        self.interior_angles = (self.sides-2)*180
        self.angle = self.interior_angles/self.sides 

I have also seen some attributes be defined within the parentheses themselves. In what cases should you do that? For example:

class Dyna_Q:
    def __init__(self, environment, alpha = alpha, epsilon = epsilon, gamma = gamma):

Thank you.


Solution

  • Regular parentheses () in programming are usually used very similarly to how they are used in math: Group stuff together and change the order of operations.

    4 - 2 == ( 4 - 2 )
    

    Will be true, however

    (4 - 2) / 2 == 4 - 2 / 2
    

    won't be. Additionally they are used, as you correctly observed, to basically tell the interpreter where a function name ends and the arguments start, so in case of a function definition they come after the name and before the :. The assignments from your last example aren't really assignments, but default values; I assume you have global variables alpha and so on in your scope, that's why this works.

    So when to use parentheses? For example:

    • When you want to change the order of operations.
    • When you want to call or define a function.
    • When you want to define inheritance of a class class Myclass(MyBaseClass): ...
    • Sometimes tuples, though return a, b and return (a,b) are the same thing.
    • As in math, extra parenthesis can be used to make the order of operations explicit, e.g. (4-2) == (4-2) to show the calculations are done before the comparison.