Cant understand dot operator concept

2020-02-16 05:58发布

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

标签: python
1条回答
对你真心纯属浪费
2楼-- · 2020-02-16 06:22

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).

查看更多
登录 后发表回答