Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #103721 > unrolled thread
| Started by | "ast" <nomail@invalid.com> |
|---|---|
| First post | 2016-02-29 16:36 +0100 |
| Last post | 2016-02-29 09:33 -0700 |
| Articles | 3 — 3 participants |
Back to article view | Back to comp.lang.python
Dynamic object attribute creation "ast" <nomail@invalid.com> - 2016-02-29 16:36 +0100
Re: Dynamic object attribute creation Random832 <random832@fastmail.com> - 2016-02-29 11:06 -0500
Re: Dynamic object attribute creation Ian Kelly <ian.g.kelly@gmail.com> - 2016-02-29 09:33 -0700
| From | "ast" <nomail@invalid.com> |
|---|---|
| Date | 2016-02-29 16:36 +0100 |
| Subject | Dynamic object attribute creation |
| Message-ID | <56d46597$0$22756$426a74cc@news.free.fr> |
Hello
Object's attributes can be created dynamically, ie
class MyClass:
pass
obj = MyClass()
obj.test = 'foo'
but why doesn't it work with built-in classes int, float, list.... ?
L = [1, 8, 0]
L.test = 'its a list !'
(however lists are mutable, int, float ... are not)
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
L.test = 'its a list !'
AttributeError: 'list' object has no attribute 'test'
but it works on functions:
def funct(a,b):
....print(a+b)
funct.test = 'this is a function'
funct.test
'this is a function'
[toc] | [next] | [standalone]
| From | Random832 <random832@fastmail.com> |
|---|---|
| Date | 2016-02-29 11:06 -0500 |
| Message-ID | <mailman.19.1456761968.20602.python-list@python.org> |
| In reply to | #103721 |
On Mon, Feb 29, 2016, at 10:36, ast wrote: > but why doesn't it work with built-in classes int, float, list.... ? > > L = [1, 8, 0] > L.test = 'its a list !' > > (however lists are mutable, int, float ... are not) Because those classes do not have attribute dictionaries, in order to save space. You can make a class without an attribute dictionary, by using __slots__.
[toc] | [prev] | [next] | [standalone]
| From | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| Date | 2016-02-29 09:33 -0700 |
| Message-ID | <mailman.23.1456763676.20602.python-list@python.org> |
| In reply to | #103721 |
On Mon, Feb 29, 2016 at 9:06 AM, Random832 <random832@fastmail.com> wrote: > On Mon, Feb 29, 2016, at 10:36, ast wrote: >> but why doesn't it work with built-in classes int, float, list.... ? >> >> L = [1, 8, 0] >> L.test = 'its a list !' >> >> (however lists are mutable, int, float ... are not) > > Because those classes do not have attribute dictionaries, in order to > save space. > > You can make a class without an attribute dictionary, by using > __slots__. You can also make a list that does have an attribute dictionary by subclassing it. >>> class MyList(list): pass ... >>> obj = MyList() >>> obj.test = 'foo'
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web