简体   繁体   中英

Import and Inheritance with Python 3.5

i have 3 python files each representing a class (i came from java, so i guess it is ok to have a class per file in python, sorry) i have a card.py file with the Card class, then i have deck.py with Deck class, and i have hand.py with Hand class. So, Hand class, inherits from Deck, but, Deck also uses a method from Hand class, but i get import errors like:

Edit//ERRORS:

jdecuirm-imac:src jdecuirm$ python3 deck.py 
Traceback (most recent call last):
  File "deck.py", line 1, in <module>
    from hand import Hand
  File "/Users/jdecuirm/Documents/workspace/chapter23_inheritance/src/hand.py", line 1, in <module>
    from deck import Deck
  File "/Users/jdecuirm/Documents/workspace/chapter23_inheritance/src/deck.py", line 1, in <module>
    from hand import Hand
ImportError: cannot import name 'Hand'
jdecuirm-imac:src jdecuirm$ 

i'll let you a gist if this help, sorry if this is a repeated question, i could not find nothing similar to my question.

https://gist.github.com/jdecuirm/82951ba7e4aa9e571819

You have a circular import because Hand imports deck and Deck imports hand.

This cannot be resolved by Python and you get the error you see here.

To fix this you really want to change the structure of your code, there really is no reason why deck should import hand. Python is dynamically typed which means you can use hand in deck without having to explicitly name types or import anything, this is very much in contrast to a language such as Java. As long as what you passed in has the correct interface everything will work.

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