提示信息

Python self

作茧 已关注

The "self" keyword in Python is a reference to the current instance of the class. It is used within class methods to access attributes and methods of that instance.

When defining a class, we refer to the current instance using the "self" parameter in method definitions. For example:

  1. class MyClass:
  2. def __init__(self, name):
  3. self.name = name
  4. def say_hello(self):
  5. print("Hello, my name is", self.name)
  6. obj = MyClass("John")
  7. obj.say_hello() # Output: Hello, my name is John

In the above example, "self" is used to refer to the instance of the class being created. It is used to access the "name" attribute of the instance within the "say_hello" method.

It is important to note that "self" is just a convention and can be replaced with any other variable name, but it is recommended to use "self" for clarity and consistency with other Python code.

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
作茧 关注 已关注

最近一次登录:2023-10-09 15:57:37   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图