kihhfeue
kihhfeue

Reputation: 55

How to use class method in another file in a class python

I have file1.py, which has a class with a method like below:

class c1:
    def m1(item):
        if item=="cool":
            return true
        return False

How can I in another python file, lets say file2.py, inherent this m1 from c1 in file1.py in a class, I first import the class:

from file1 import c1

Can I do the inherence like below (using the same class and method name from file1.py in file2?)

class c1:
    def m1(item):
        c1.m1(item)

Upvotes: 0

Views: 115

Answers (2)

just a stranger
just a stranger

Reputation: 320

You don't need to use the same class name and function in file 2.

for example:

#file1

class c1:
    def m1(self, item):
        if item=="cool":
        return True
    return False

from file1 import c1
class another_class:
    def do_something(self, item):
        c1.m1(item)

print(another_class().do_something("cool"))

Again, both do not need to have the same class and function name, but using different names will avoid confusion in long projects.

Upvotes: 1

Seth
Seth

Reputation: 2370

With a couple of modifications to the files you've shown above, yes this would be possible. Here's my working version of this:

# file1.py

class c1:
    def m1(self, item):
        if item=="cool":
            return True
        return False
# file2.py

import file1

class c1:
    def m1(self, item):
        return file1.c1().m1(item)

test = c1()
print(test.m1("cool"))

Upvotes: 1

Related Questions