python中的Self需要帮助吗

2024-09-30 16:29:38 发布

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

有人能解释一下为什么写这个代码是abc.name而不是mysillyobject.name吗

class Person:
  def __init__(mysillyobject, name, age):
    mysillyobject.name = name
    mysillyobject.age = age

  def myfunc(abc):
    print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()

https://www.w3schools.com/python/gloss_python_self.asp


Tags: 代码namehelloageinitismydef
2条回答
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def myfunc(self):
    print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

输出:你好,我叫约翰

请参阅>; https://www.python.org/dev/peps/pep-0008/

Function and Method Arguments

Always use self for the first argument to instance methods.

Always use cls for the first argument to class methods.

If a function argument's name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus class_ is better than clss. (Perhaps better is to avoid such clashes by using a synonym.)

这是由于第二个函数的输入参数为“abc”。如果将输入更改为“self”参数,则应使用self.name

相关问题 更多 >