M. Phys
M. Phys

Reputation: 147

Why have a class with both a class variable and an instance variable of the same name?

I've seen a few snippets of code in different languages where a class has a class variable, but then in the same class, there's also an instance variable of the same name. I'm trying to understand why we would do this? What would be the benefits of doing something like this:

class Paint:

    colour = 'red'

    def __init__(self, name, counter):        
        self.id = name        
        self.colour = colour

This is in Python and just an example. I'm trying to understand the benefits, and why someone would do this, in any programming language, but particularly C++, ruby, and python.

Upvotes: 3

Views: 1581

Answers (3)

Yas
Yas

Reputation: 5461

Define default values:

class C:
    x = 1

    def __init__(self, x = None):
        if x is None:
            self.x = self.x
        else:
            self.x = x
    
c1 = C()
print(c1.x) # 1
c2 = C(2)
print(c2.x) # 2

Upvotes: 0

6502
6502

Reputation: 114461

In Python that can be used for defaults.... for example:

class Foo:
    x = 1

a = Foo()
b = Foo()
print(a.x, b.x) # --> 1 1
a.x = 2
print(a.x, b.x) # --> 2 1

Upvotes: 5

tdao
tdao

Reputation: 17678

where a class has a class variable, but then in the same class there's also an instance variable of the same name.

Class variable or member variable allocates the memory of that variable for every single object of the same class. It may or may not have default value, like the colour = 'red' in your example.

Instance variable is specific to individual object of that class. Every single object must initialise that instance variable in some way, or optionally having default value.

Upvotes: 1

Related Questions