python中的类为什么可以这样子直接调用啊,如下


import rospy
import cv2
from std_msgs.msg import String
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image
class fake_camera:
    def __init__(self):
        self.image_path = rospy.get_param('~image_path','bingda.png')
        self.image_pub = rospy.Publisher("/image_static", Image, queue_size=3)
        self.bridge = CvBridge() 
        self.pub_image()
    def pub_image(self):
        
        self.rate = rospy.Rate(30)
        print self.image_path
        self.cv_image = cv2.imread(self.image_path,1)
        rospy.loginfo("Start Publish Fake Camera Image")
        while not rospy.is_shutdown():
            img_msg = self.bridge.cv2_to_imgmsg(self.cv_image, "bgr8")
            img_msg.header.stamp = rospy.Time.now()
            self.image_pub.publish(img_msg)
            self.rate.sleep()

if __name__ == '__main__':
    try:
        rospy.init_node("fake_camera",anonymous=False)
        fake_camera()
    except rospy.ROSInternalException:
        pass

主函数里的fake_camera()不是一个类吗,怎么直接当成函数用了?

类直接调用就是创建一个实例对象,执行类的构造函数__init__(),并返回创建的实例对象
一般是
obj = fake_camera()
obj是返回的实例对象
你这样
fake_camera()
是只执行了类的构造函数__init__(),没有接收返回的实例对象
等同其它语言的 new fake_camera()
只是python语言不需要 new 而已,语法上就和函数调用一样了

它相当于n = fake_camera()然后没有调用n,可以看到fake_camera拥有一个无参的初始化函数,所以fake_camera()就是实例化类fake_camera,只不过没有保存到变量里面