简体   繁体   中英

Why doesn't this Python work? Simple Oop

class UserDict: 
    def __init__(self, dict=None):             
        self.data = {}                         
        if dict is not None: self.update(dict)

I created a file "abc.py" and put above in it.

>>> import abc
>>> d = abc.UserDict()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'UserDict'

Most certainly you are importing the Python abc module for abstract base classes instead of your own abc.py . Better choose a different name for your module.

Edit: Of course it is possible to have your own module with the same name as a built-in module and to import it. You have to make sure that your module is in the interpreter's working directory or set the Python path correctly. But it is much easier to avoid the name clash -- in particular in this case, where you presumably don't care about the module's name anyway.

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