hey guys am really confused about the working of dot operator..The code which i have tried..
class Name:
class x:
def __init__(self,y):
self.y = y
def __init__(self):
pass
some = Name()
some.x.y = 'foo'
print some.x.y
When i run this code it succesfully outputs foo
.
But when i tried the code
class Name:
class x:
def __init__(self,y,z):
self.y = y
self.z = z
def __init__(self):
pass
some = Name()
some.x.y.z = 'foo'
print some.x.y.z
i get an error..how can i use like some.x.y.z
and get the output as foo
??..
Any useful help would be appreciated..Thanks
It is not clear why you expected the second code to work. The first code is bad, as it mixes up classes and instances:
some
is an instance of the className
;some.x
is a class, and also a class attribute ofName
. If you create anotherName
instance, it will share the same attributes onx
. Instead, consider this:The result looks like:
You can't try to access arbitrary chains of attributes
a.b.c.d
and expect them to work; you have to define the attributes your object should have (until you get into e.g.__getattr__
, but let's not worry about that now). You can't add arbitrary attributes to e.g. strings orNone
(so you can't now setsome.x.y.z.foo = 'bar'
), although you can to your own classes (so you could setsome.x.y.bar = 'baz'
). However you can't do e.g.some.x.y.foo.bar = 'baz'
, becausesome.x.y.foo
doesn't exist (yet).