python - self 做什么?

标签 python self args

<分区>

Possible Duplicate:
Python 'self' keyword

如果这是一个非常菜鸟的问题,请原谅我,但我从来没有在 Python 中理解 self。它有什么作用?当我看到类似的东西时

def example(self, args):
    return self.something

他们是做什么的?我想我也曾在某个函数的某处看到过 args。请用简单的方式解释:P

最佳答案

听起来您已经无意中发现了 Python 的面向对象特性。

self 是对对象的引用。它与许多 C 风格语言中的 this 概念非常接近。查看这段代码:

class Car(object):

  def __init__(self, make):

      # Set the user-defined 'make' property on the self object 
      self.make = make

      # Set the 'horn' property on the 'self' object to 'BEEEEEP'
      self.horn = 'BEEEEEP'

  def honk(self):

      # Now we can make some noise!
      print self.horn

# Create a new object of type Car, and attach it to the name `lambo`. 
# `lambo` in the code below refers to the exact same object as 'self' in the code above.

lambo = Car('Lamborghini')
print lambo.make
lambo.honk()

关于python - self 做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6698030/

相关文章:

python - 可迭代解包和切片分配

python - 复制列表 : editing copy without changing original

python - 为什么使用外部函数传递和更改类自变量可以操作可迭代对象,但不能操作变量?

Bash - ack - 限制匹配行的长度

Python 访问变量

python - 如何使用Python中的同义词在 Elasticsearch 中搜索查询

python - self 参数是如何神奇地传递给实例方法的?

rust - 在特征实现的上下文中理解 'self' 参数

java - 只需声明其总和和处理延迟即可从 args 读取输入文件

c++ - 为存储为数组的 Variadic 模板函数调用解压数据(目标 :RPC)