Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 405
M. Phys Avatar asked Nov 17 '25 23:11

M. Phys


1 Answers

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
like image 118
6502 Avatar answered Nov 20 '25 12:11

6502



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!