Home > other >  Classes in Python - when to use parentheses
Classes in Python - when to use parentheses

Time:03-25

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.

CodePudding user response:

In python's constructor function, the 'self' points to the current object to be created.

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

The fact is that, if you have a ready value to be set inside the newly created object you will pass that value to the constructor inside the parenthesis.

But if you don't know that value to put inside your new object and also the value needs to be calculated you wont pass the value inside parenthesis.

The core thing is understanding the 'self' keyword. If you do self.<property_name> = , you are creating a new property(field) inside your object.

CodePudding user response:

Regular parentheses () in programming are usually used very similarly to how they 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 method 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) is 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.

CodePudding user response:

The __init__ method is the object constructor. It means that his arguments are the basic parameters that you need in order to initialize each object instance.

On the other side, "interior_angles" and "angle" are calculated attribute based on sides.

  • Related