-2
votes

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

1
Don't you mean self.x.z? - EdChum
You can use some.x.y and some.x.z. But z isn't inside y, so why would you expect some.x.y.z to work? - Barmar
@Barmar can you please post it as an answer - user3843420
Note that the __init__ of your nested class is never called, because you never instantiate the class. When you set ``some.x.y` you're setting a class attribute on some.x. In some sense this doesn't matter, since x is itself a class variable, but it suggests you're not really understanding what your code is doing. What are you trying to accomplish here? - BrenBarn
@user3843420: Why do you want to do some.x.y.z? Rather than talking about syntax, can you describe the meaning of what you want to do? - user2357112 supports Monica

1 Answers

3
votes

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 class Name; some.x is a class, and also a class attribute of Name. If you create another Name instance, it will share the same attributes on x. Instead, consider this:

class Name(object):
    def __init__(self, x=None,
                 y=None, z=None):
        self.x = x
        self.y = y
        self.z = z

y = Name(z='foo')
x = Name(y=y)
some = Name(x=x)

##some = Name(x=Name(y=Name(z='foo'))) # one-line equivalent

print some.x.y.z # 'foo'

The result looks like:

 - some: Name
   - x: Name
     - x: None
     - y: Name
       - x: None
       - y: None
       - z: 'foo'
     - z: None
   - y: None
   - z: None

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 or None (so you can't now set some.x.y.z.foo = 'bar'), although you can to your own classes (so you could set some.x.y.bar = 'baz'). However you can't do e.g. some.x.y.foo.bar = 'baz', because some.x.y.foo doesn't exist (yet).