-2

How should I define the attributes of a class?

class Example:

   def __init__(self,n,m):
     self.n=n
     self.m=m

or in this way:

class Example:
  m=0
  n=0

  def __init__(self,n,m):
    self.n=n
    self.m=m

If I define an attribute outside the constructor, is it a static variable?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ohad
  • 1,563
  • 2
  • 20
  • 44
  • It depends - do you want them to be *class attributes* (shared by all instances) or *instance attributes* (individual to each instance)? – jonrsharpe Jun 17 '14 at 12:06

2 Answers2

4

I think you are confusing instance variables and variables of the class itself (you could call them static if you are coming from java). Have a look at this demo (note that __init__ needs two underscores).

class Example:
    m=0
    n=0

    def __init__(self,n,m):
        self.n=n
        self.m=m

e = Example(1,2)
print(e.m) # 2
print(e.n) # 1
print(Example.m) # 0
print(Example.n) # 0

In your second code, Example has the class variables m and n, and each instance of an Example object will have instance members self.m and self.n.

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • yes I am coming from Java... so m and n are like class variables (static variable) in Java, and self.n and self.m are object variables... and I do not need to define them outside the constructor.. – Ohad Jun 17 '14 at 12:08
  • @Shiran yes, if you don't want the `Example` class itself (as opposed to instances of that class) have the attributes `n` and `m` there's no need for the first two lines after `class Example`. – timgeb Jun 17 '14 at 12:10
3

This way:

class Example:

  def __init__(self,n,m):
    self.n=n
    self.m=m

Double score the init, like this: __init__, not like this _init_!

m=0 and n=0 are class attributes, and don't have anything with self.n and self.m, which are instance variables.

Reloader
  • 742
  • 11
  • 22