-2
Class sampleclass:
      constant = 10
def __init(self,value)
      self.value = value *10 + constant


x = sampleclass(2)
print (x.value) #prints the calculated value
print(x.constant) #prints the constant

Question: I do not want 'x' to access 'constant' value, How can i restrict this or is there any other way to declare constant?

GPhilo
  • 18,519
  • 9
  • 63
  • 89

1 Answers1

0

Python is not designed to do this as you can see here.

But if you really want that you have to override the getter and setter of the constant.

In your case you could do this:

class Sampleclass:
    def __init__(self,value):
        self.value = value * 10 + self.constant

    @property
    def constant(self):
        return 10

The @property constant returns the integer 10

because is only a @property without a corrosponding setter you cannot change the value

Kumpelinus
  • 640
  • 3
  • 12