I tried executing this piece of code in my Idle and have the following error,
class Myclass():
i = 1
x = Myclass()
x.y = 10
x.i=10
x.i
# 10
x.y
# 10
This class has only 1 attribute 'i', but when I assign x.y = 10, how will Python allow it to work. Isn't that a problem? How do I prevent it happening?
As other answers have mentioned, this is a feature not a bug.
If you want to enforce only a limited set of attributes, you can use __slots__ with new-style classes (classes that inherit from object):
class Myclass(object):
__slots__ = ['i']
>>> x = Myclass()
>>> x.i = 10
>>> x.y = 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Myclass' object has no attribute 'y'
Python, unlike many other languages like Java, assigns class members dynamically. That means that you don't need to include a variable in the class's definition to be able to assign to it.
Also note that there is a difference between a class variable like the one you are assigning:
class Myclass():
i = 1
and a class member:
class Myclass():
def __init__(self):
self.i = 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With