自我做什么?

发布于 2024-11-20 00:01:36 字数 352 浏览 4 评论 0原文

可能的重复:
Python“self”关键字

请原谅我,如果这是一个令人难以置信的菜鸟问题,但我从来没有理解 self Python。它有什么作用?当我看到

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

他们在做什么时?我想我也在函数中的某个地方看到了 args 。请简单解释一下:P

Possible Duplicate:
Python 'self' keyword

Forgive me if this is an incredibly noobish question, but I never did understand self in Python. What does it do? And when I see things like

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

what do they do? I think I've seen args somewhere in a function too. Please explain in a simple way :P

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

老子叫无熙 2024-11-27 00:01:36

听起来您好像偶然发现了 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()

It sounds like you've stumbled onto the object oriented features of Python.

self is a reference to an object. It's very close to the concept of this in many C-style languages. Check out this code:

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()
花间憩 2024-11-27 00:01:36

self 是对该方法(在本例中为 example 函数)所属类的实例的引用。

您需要查看 Python 文档关于类系统,全面介绍 Python 的类系统。您还需要查看这些答案 其他 有关的问题 主题 Stackoverflow

self is the reference to the instance of the class that the method (the example function in this case) is of.

You'll want to take a look at the Python docs on the class system for a full introduction to Python's class system. You'll also want to look at these answers to other questions about the subject on Stackoverflow.

很快妥协 2024-11-27 00:01:36

它本身是对当前类实例的引用。在您的示例中,self.something 引用 example 类对象的 something 属性。

Self it a reference to the instance of the current class. In your example, self.something references the something property of the example class object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文