noober
noober

Reputation: 1505

python - how to properly import a method from a class in another file

Python newbie here. I'm having problems trying to import and/or use a method from a class that I've created which I created a "/lib" directory for.

Here is my current file tree:

/tokenmgt
         /lib/myToken.py

From the directory:

/tokenmgt

I am running the python from the command line in this directory. I want to use the "create" method defined in my class "TokenMgr":

class TokenMgr():
    """Model a Token Manager"""

    def __init__(self):
        pass
    
    def create(self, privkey, email):
        """<REST OF CODE HERE>"""  

I'm getting these errors:

Type "help", "copyright", "credits" or "license" for more information.
>>> import lib.myToken
>>> from lib.myToken import create
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'create' from 'lib.myToken' (C:\Users\FOO\Desktop\MyWork\dev\lib\myToken.py)

Do I need to also import the class name ("TokenMgr" defined in the .py script? I'm confused how to do this properly. Thanks

Upvotes: 0

Views: 1392

Answers (2)

Arun Kaliraja Baskaran
Arun Kaliraja Baskaran

Reputation: 1086

The create method can be accessed only through an object. So you should import your class, create an instance and then do instance.create().. if you feel the create should not be tied to any object u can decorate it using @classmethod, so that you can access without an object..

Here are a bit of basics. Pythons classes can have three types of routines.

  1. Instance methods -> These are tied to an object, they receive self as the first argument, which is the object
  2. Class methods -> Which are common for all objects of a class, and the first argument is cls for these methods instead of self
  3. Static methods -> They are also tied to a class, but they neither receive class or object instance as their first argument. This is as good as having a standalone function, outside a class definition.

2 and 3 are achieved with @classmethod and @staticmethod decorators respectively like below:

In [6]: B.create(10) In static create method..

In [7]: class A:
   ...:     @classmethod
   ...:     def create(cls,x):
   ...:         print("In create method with args {},{}".format(cls, x))
   ...:
   ...:

In [8]: A.create(10)
In create method with args <class '__main__.A'>,10


In [4]: class B:
   ...:     @staticmethod
   ...:     def create(x):
   ...:         print("In static create method..")
   ...:

In [6]: B.create(10)
In static create method..

In your case you can use either of them based on your requirement or create an object of the TokenManager class and then call create method like below:

tokenManager_obj = TokenManager()
tokenManager_obj.create()

Upvotes: 1

bensha
bensha

Reputation: 69

This is the proper way to import and use a class:

from lib.MyToken import TokenMgr
manager = TokenMgr()
manager.create(private_key,'[email protected]')

Note the second line, in which we create an instance of the class.

Upvotes: 1

Related Questions