Class variable and instance variable issue in Python

When I have this class, the variable 'value' is a class variable.

class Hello:
    value = 10
    def __init__(self):
        print 'init'

I have an object "h" and I can get the same value "10" for both Hello.value and h.value.

h = Hello()
print Hello.value
print h.value

When I ran this command,

h.value = 20

I get the value "10" and "20" when I run them.

print Hello.value
print h.value

Why is this?

  • Q1: Why does "print h.value" output the value Hello.value and not cause an error?
  • Q2: Does h.value = 20 introduce a new variable like "self.value = 20"?
  • Q3: Is there a way to prevent the creation of an instance variable (or prevent the execution of the code "h.value = 20")?
+3
source share
2 answers

, Python:

  • , , , .

  • , - , , .

, __setattr__(), , , , , . __slots__ = [] .

+4

Python o.attr, , , .. , (.. ).

.

  • A1. ( , )

  • A2. , .

  • A3. __setattr__ , .

+4

Source: https://habr.com/ru/post/1786018/


All Articles