简体   繁体   中英

How to import a class' function to another .py in the same directory?

Forgive me, I am new to coding in Python and trying to learn the basics... I am trying to import classA's function "functionA" into classB to use the function. For example:

class classA():
   def functionA():
      print("Jello World!")

Now I have this on one .py, let's say it's called "sampleA.py" in the same directory called "directory". Now the question is, how do I make it so I can use classA's function "functionA" in classB and have classB on another file called "sampleB.py" in the same directory.

I am so sorry if this is confusing but I want to figure out how to make it so, it's something like:

class classB():
   classA.functionA()

And this would print "Jello World!"

Simple, like this:

from sampleA import classA

You can now call functionA like this:

classA.functionA()

Using your code:

sampleA.py

class classA():
   def functionA():
      print("Jello World!")

sampleB.py

from sampleA import classA

class classB():
    def __init__(self):
        classA.functionA()

I added an __init__ function to classB so functionA gets executed immediately. Important caveat: sampleA.py and sampleB.py must be in the same directory.

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