3

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.

4
  • 3
    If it’s exactly like this, it’s rather superfluous. However, if the assignment inside __init__ is conditional somehow, the class attribute would act as a default value. Commented Sep 5, 2020 at 7:27
  • Can you please post working code? Your code is not syntactically legal Ruby code. There are no class variables in your code, class variables start with a @@ double at sigil. Also, there are no instance variables in your code, instance variables start with a @ at sigil. Commented Sep 5, 2020 at 11:02
  • The question is general. I'm trying to understand why someone would do this, and if their are any language-specific brnefits. Commented Sep 5, 2020 at 11:58
  • It is not clear what you are asking, because there are no class variables in your code. Class variables start with @@. The variables in your code are local variables. At least, they would be in Ruby, which is what your question is tagged with. Commented Sep 5, 2020 at 13:29

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.