Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

If I have two classes, and one of them has a function that I want to use in my other class, what do I use so that I don't have to rewrite my function?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
587 views
Welcome To Ask or Share your Answers For Others

1 Answer

There are two options:

  • instanciate an object in your class, then call the desired method on it
  • use @classmethod to turn a function into a class method

Example:

class A(object):
    def a1(self):
        """ This is an instance method. """
        print "Hello from an instance of A"

    @classmethod
    def a2(cls):
        """ This a classmethod. """
        print "Hello from class A"

class B(object):
    def b1(self):
        print A().a1() # => prints 'Hello from an instance of A'
        print A.a2() # => 'Hello from class A'

Or use inheritance, if appropriate:

class A(object):
    def a1(self):
        print "Hello from Superclass"

class B(A):
    pass

B().a1() # => prints 'Hello from Superclass'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...