Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python class definition assigning attributes

Tags:

python

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?

like image 519
user1050619 Avatar asked Feb 03 '26 13:02

user1050619


2 Answers

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'
like image 168
Andrew Clark Avatar answered Feb 06 '26 02:02

Andrew Clark


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
like image 29
David Robinson Avatar answered Feb 06 '26 01:02

David Robinson