Can Python subclasses override global functions?
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-05-18 10:46:14
0
2
465

For example, there is a class A

in a.py

A has several methods, all of which call a global function hello() (defined outside the class, but also in a.py).

Suppose I want to write a subclass B, but I want B to call a newly defined hello(). Is this possible?

# a.py
# hello() 不在类的声明里
def hello():
    print "Hello"
    
class A(object):
    # 调用全局函数 hello()
    def greeting(self):
        hello()
# b.py
class B(A):
    # 想要重载hello()从而使greeting 的输出改变

Do not change greeting, but want output like this:

b = B()
b.greeting()
'Hi'

曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(2)
大家讲道理

It seems that you need to use inheritance.

漂亮男人

Thanks for the invitation.

Sorry, I don’t fully understand your needs yet, so I’ll answer it theoretically first. If the questioner can add something, I can further improve my answer and give the code that can solve the problem.

In Python, if a method can be logically put together with a class. Then you can use this method as a static method of the class, that is, decorate it with @staticmethod.

If you will hello()作为类A和类B的静态方法,那么在各自的类中用cls.hello()就可以调用各自版本的hello.

According to the description of the subject, it contains hello(),那么我想将其作为静态方法是没有问题的。如果有其他模块想要调用a.py中的hello(),可以直接使用A.hello() in category B.

Please correct me if I misunderstand the question’s requirements.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!