简体   繁体   中英

assigning variable to object python

Does the object keyword have any uses except for classes like:

class HelloWorld(object):
    pass

Because when assigning a variable to object it seems as if there is no use for it (no variable.__dict__ or anything).

for example:

x=object()
x.anything="foo"#<----- throws an error

One possible use is for sentinel values - things that you want to have unique values that can't be duplicated by accident. For instance:

NOT_SET = object()

def some_function(arg=NOT_SET):
    if arg is NOT_SET:
        # the user didn't pass in a value for 'arg'
     else:
        # the user passed in a value for 'arg'

Because every object instance has a unique identity, the if statement's condition will only be true if the user didn't pass in a value (unlike the common default value for a parameter, None , which the user might pass in to some functions).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM