在属于类的函数中定义变量

2024-10-02 22:29:55 发布

您现在位置:Python中文网/ 问答频道 /正文

在代码中,有一个类具有名为“goal_callback”的函数。在函数中,使用.init前缀定义变量,其他变量通常不使用前缀定义。 我知道,自我。前缀用于使变量成为“类变量”,以便类中的每个函数都可以访问它。所以在代码中,我只有一个函数,如果我们用self定义变量,会有什么不同吗。前缀与否。 “起飞”变量和“起飞”或“着陆”变量之间的差异到底是什么

#! /usr/bin/env python

class CustomActionMsgClass(object):
  def __init__(self):
    self._as = actionlib.SimpleActionServer("action_custom_msg_as", CustomActionMsgAction, 
    self.goal_callback, False)
  def goal_callback(self, goal): 
    success = True
    r = rospy.Rate(1)
    self._pub_takeoff = rospy.Publisher('/drone/takeoff', Empty, queue_size=1)
    self._takeoff_msg = Empty()
    self._land_msg = Empty()
    # Get the goal word: UP or DOWN
    takeoff_or_land = goal.goal #goal has attribute named 'goal'. 
if __name__ == '__main__':
 rospy.init_node('action_custom_msg')
 CustomActionMsgClass()
 rospy.spin()

Tags: 函数代码self定义initdefascallback
1条回答
网友
1楼 · 发布于 2024-10-02 22:29:55

下面是对象级和类级变量的示例

class A(object):
    Z = 3  # class variable. Upper-case is good code style for class-level variables
           # defined inside the class but outsize of it's methods
    def __init__(self):
        self.x = 1  # object variable
        y = 2       # local variable; it will lost after returning from the function
    def some_method(self):
        self.w = 4  # object variable too
        # Note that it is not recommended to define
        # object variables outside of __init__()

在代码中_pub_takeoff是对象的变量takeoff_or_land是局部变量

相关问题 更多 >