Static VS Instance Variables: Difference

Static vs Instance Variables: Difference?

In the context of class attributes, static has a different meaning. If you have a field like:

private static int sharedAttribute;

then, each and every instance of the class will share the same variable, so that if you change it in one instance, the change will reflect in all instances, created either before or after the change.

Thus said, you might understand that this is bad in many cases, because it can easiy turn into an undesired side-effect: changing object a also affects b and you might end up wondering why b changed with no apparent reasons. Anyway, there are cases where this behaviour is absolutely desirable:

  1. class constants: since they are const, having all the classes access the same value will do no harm, because no one can change that. They can save memory too, if you have a lot of instances of that class. Not sure about concurrent access, though.
  2. variables that are intended to be shared, such as reference counters &co.

static vars are instantiated before your program starts, so if you have too many of them, you could slow down startup.

A static method can only access static attributes, but think twice before trying this.

Rule of thumb: don't use static, unless it is necessary and you know what you are doing or you are declaring a class constant.

Performance difference between static and instance variables

It's not a matter of performance. static and instance variables have a different purpose.

Using

int i = new MyInstatnceClass().getMyNonStaticInt();

is almost certainly useless, since each time you call new MyInstatnceClass() you create a new MyInstatnceClass instance, having a new myNonStaticInt instance variable. Since you are not keep a reference to the created instance, you cannot retrieve the same instance variable twice, which makes it useless.

If you need a single copy of a variable to be shared across all instances of the class, static variable is the way to go.

That said, the latter call is also more expansive, since it involves creation and initialization of an instance of your MyInstatnceClass class (in addition to loading and initialzing the class if it's the first access that class).

On the other hand, MyStaticClass.getMyStaticInt() only loads and initializes the class MyStaticClass if it's the first access of that class. It doesn't have to create any instance of that class.

What is the difference between an instance and a class (static) variable in Java

A static variable is shared by all instances of the class, while an instance variable is unique to each instance of the class.

A static variable's memory is allocated at compile time, they are loaded at load time and initialized at class initialization time. In the case of an instance variable all of the above is done at run time.

Here's a helpful example:

An instance variable is one per object: every object has its own copy of its instance variable.

public class Test{

int x = 5;

}

Test t1 = new Test();
Test t2 = new Test();

Both t1 and t2 will have their own copy of x.

A static variable is one per class: every object of that class shares the same static variable.

public class Test{

public static int x = 5;

}

Test t1 = new Test();
Test t2 = new Test();

Both t1 and t2 will share the same x.

Difference between Static methods and Instance methods

The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.

However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.

You can do this to execute a static method:

MyClass.staticMethod();  // Simply refers to the class's static code

But to execute a non-static method, you must do this:

MyClass obj = new MyClass();  //Create an instance
obj.nonstaticMethod(); // Refer to the instance's class's code

On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.

Java Static vs Instance

1. An instance variable is one per Object, every object has its own copy of instance variable.

Eg:

public class Test{

int x = 5;

}

Test t1 = new Test();
Test t2 = new Test();

Both t1 and t2 will have its own copy of x.

2. A static variable is one per Class, every object of that class shares the same Static variable.

Eg:

public class Test{

public static int x = 5;

}

Test t1 = new Test();
Test t2 = new Test();

Both t1 and t2 will have the exactly one x to share between them.

3. A static variable is initialized when the JVM loads the class.

4. A static method cannot access Non-static variable or method.

5. Static methods along with Static variables can mimic a Singleton Pattern, but IT'S NOT THE RIGHT WAY, as in when there are lots of classes, then we can't be sure about the class loading order of JVM, and this may create a problem.

Differences between static and instance variables in python. Do they even exist?

class SomeClass:
x=6 # class variable

def __init__(self):
self.y = 666 # instance variable

There is virtue in declaring a class scoped variable: it serves as default for one. Think of class scoped variable as you would think of "static" variables in some other languages.

Static variable vs class variable vs instance variable vs local variable

I believe that static and class variables are commonly used as synonyms.

What you say about the variables is correct from the convention point of view: this is how you should think about them most of the time.

However the above are just conventions: from the language point of view there is no distinction between class variables and instance variables.

Python is not like C++ or Java.

Everything is an object, including classes and integers:

 class C(object): pass
print id(C)
C.a = 1
assert C.__dict__['a'] == 1

There is no clear distinction between methods and instance variables: they are just attributes of an object.

Therefore, there is no language level distinction between instance variables and class variables: they are just attributes of different objects:

  • instance variables are attributes of the object (self)
  • class variables are attributes of the Class object.

The real magic happens on the order that the . operator searches for attributes:

  • __dict__ of the object
  • __dict__ of the class of the object
  • MRO up to parent classes

You should read this great article before you get confused in the future.

Also beware of bound vs unbound methods.

EDIT: attempt to address further questions by the OP made in his post.

Wow that was large! I'll try to read everything, but for the future you should try to keep questions more concice. More code, less talk =). You'll get better answers.

should I just keep the idea in mind and not worry too much about reconciling my current point of view with that one until I become more experienced?": I do things.

I do as I feel necessary. When necessity calls, or I can't take magic behaviour anymore, I learn.

sort of imply that the Python documentation explains this point of view somewhere within it?

I don't know about the docs, but the language itself works that way.

Of course, the language was designed to give the impression that syntax works just like in C++ in the common cases, and it adds a thin layer of magic to classes to make it look like so.

But, since that is not how it truly works, you cannot account for all (useful) behaviour by thinking only in terms of C++ class syntax.

By using the code from the original post, is there maybe a sequence of commands that illustrates this point?

I'm not sure it can be illustrated in sequence of commands. The point is: classes are objects, and their attributes are searched by the dot . MRO on the same order as attributes of objects:

class C(object):
i_static = 0
def __init__(self):
self.i = 1

# i is in the __dict__ of object c
c = C()
assert c.__dict__['i'] == 1
assert c.i == 1

# dot finds i_static because MRO looks at class
assert c.__class__.__dict__['i_static'] == 0
assert c.i_static == 0

# i_static is in the __dict__ of object C
assert C.__dict__['i_static'] == 0
assert C.i_static == 0

# __eq__ is in the dict of type, which is the __class__ of C
# By MRO, __eq__ is found. `C,C` because of bound vs unbound.
assert C.__class__.__dict__['__eq__'](C,C)
assert C == C

are there just the two scopes of global and local involved in that program?

This is a point I don't know very clearly.

There is a no global scope in Python, only module level.

Then there is a new local scope inside functions.

The rest is how the . looks for attributes.

can't pinpoint exactly what I was trying to ask

Ask: can I find a difference in syntax between classes, integers or functions?

If you think you have found one, ask: hmmm, how can I make an object with certain attributes that behaves just like that thing which does not look like an object?

You should find an answer every time.

Example:

def f(): pass

class C(object): pass

AHA: f is different than c = C() because I can do f() but notc()`!

But then, no, it is just that the f.__class__.__dict__['__call__'] attribute is defined for f, and can be found via MRO.

But we can do that for c too:

class C(object):
def __call__(self): pass

and now we can do c().

So they were not different in that aspect.

Difference between accessing static instance variables using the keyword this and Class name

They are both equivalent.

However, accessing static members using this is misleading and should be avoided at all costs.



Related Topics



Leave a reply



Submit