繁体   English   中英

`self` 参数的用途是什么? 为什么需要它?

[英]What is the purpose of the `self` parameter? Why is it needed?

考虑这个例子:

class MyClass:
    def func(self, name):
        self.name = name

我知道self指的是MyClass的特定实例。 但是为什么func必须明确地包含self作为参数呢? 为什么我们需要在方法的代码中使用self 其他一些语言使这成为隐含的,或者使用特殊的语法。


对于language-agnostic考虑设计决策,请参阅强制显式 this/self 指针有什么好处? .

要关闭 OP 省略方法的self参数并获得TypeError调试问题,请使用TypeError:method() 采用 1 个位置参数,但给出了 2 个 如果 OP 省略了self. 在方法的主体中并得到一个NameError ,考虑如何在 class 中调用 function? .

你需要使用self. 是因为 Python 不使用@语法来引用实例属性。 Python 决定以一种使方法所属的实例自动传递但不自动接收的方式来执行方法:方法的第一个参数是调用该方法的实例。 这使得方法与函数完全一样,并留给您使用实际名称(尽管self是惯例,当您使用其他东西时人们通常会皱眉头。) self对于代码来说并不特殊,它只是另一个对象。

Python 可以做一些其他的事情来区分普通名称和属性——像 Ruby 那样的特殊语法,或者像 C++ 和 Java 那样需要声明,或者更不同的东西——但它没有。 Python 完全是为了让事情变得明确,让事情变得显而易见,尽管它并不完全在任何地方都这样做,但它确实可以为实例属性做到这一点。 这就是为什么分配给实例属性需要知道要分配给哪个实例,这就是为什么它需要self. .

假设您有一个ClassA类,其中包含一个方法methodA定义为:

def methodA(self, arg1, arg2):
    # do something

ObjectA是此类的一个实例。

现在,当ObjectA.methodA(arg1, arg2)时,python 在内部为您将其转换为:

ClassA.methodA(ObjectA, arg1, arg2)

self变量是指对象本身。

让我们看一个简单的向量类:

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

我们想要一个计算长度的方法。 如果我们想在类中定义它会是什么样子?

    def length(self):
        return math.sqrt(self.x ** 2 + self.y ** 2)

当我们将其定义为全局方法/函数时,它应该是什么样子?

def length_global(vector):
    return math.sqrt(vector.x ** 2 + vector.y ** 2)

所以整个结构保持不变。 我怎么能利用这个? 如果我们暂时假设我们没有为Vector类编写length方法,我们可以这样做:

Vector.length_new = length_global
v = Vector(3, 4)
print(v.length_new()) # 5.0

这是因为length_global的第一个参数可以重新用作length_new中的self参数。 如果没有明确的self ,这是不可能的。


另一种理解显式self需求的方法是查看 Python 在哪里添加了一些语法糖。 当你记住时,基本上,一个电话就像

v_instance.length()

内部转化为

Vector.length(v_instance)

很容易看出self的位置。您实际上并没有在 Python 中编写实例方法; 你写的是类方法,它必须将实例作为第一个参数。 因此,您必须将实例参数明确放置在某处。

实例化对象时,将对象本身传递给 self 参数。

在此处输入图像描述

因此,对象的数据被绑定到对象。 下面是一个示例,说明您可能希望如何可视化每个对象的数据可能看起来的样子。 请注意“self”是如何替换为对象名称的。 我并不是说下面的这个示例图是完全准确的,但它希望能够用于可视化 self 的使用。

在此处输入图像描述

Object 被传递到 self 参数中,以便对象可以保留自己的数据。

虽然这可能并不完全准确,但请考虑像这样实例化对象的过程:当创建一个对象时,它使用类作为其自己的数据和方法的模板。 如果不将它自己的名称传递给 self 参数,则类中的属性和方法将保留为通用模板,并且不会被引用(属于)对象。 因此,通过将对象的名称传递给 self 参数,这意味着如果从一个类实例化 100 个对象,它们都可以跟踪自己的数据和方法。

请参见下图:

在此处输入图像描述

我喜欢这个例子:

class A: 
    foo = []
a, b = A(), A()
a.foo.append(5)
b.foo
ans: [5]

class A: 
    def __init__(self): 
        self.foo = []
a, b = A(), A()
a.foo.append(5)
b.foo
ans: []

我将使用不使用类的代码进行演示:

def state_init(state):
    state['field'] = 'init'

def state_add(state, x):
    state['field'] += x

def state_mult(state, x):
    state['field'] *= x

def state_getField(state):
    return state['field']

myself = {}
state_init(myself)
state_add(myself, 'added')
state_mult(myself, 2)

print( state_getField(myself) )
#--> 'initaddedinitadded'

类只是一种避免一直传递这种“状态”事物的方法(以及其他好的事物,如初始化、类组合、很少需要的元类,以及支持覆盖操作符的自定义方法)。

现在让我们使用内置的 python 类机制来演示上面的代码,以展示它是如何基本相同的。

class State(object):
    def __init__(self):
        self.field = 'init'
    def add(self, x):
        self.field += x
    def mult(self, x):
        self.field *= x

s = State()
s.add('added')    # self is implicitly passed in
s.mult(2)         # self is implicitly passed in
print( s.field )

[从重复的封闭问题中迁移了我的答案]

以下摘录来自关于 self 的 Python 文档

与在 Modula-3 中一样,[在 Python 中] 没有用于从其方法中引用对象成员的简写:方法函数使用表示对象的显式第一个参数声明,该参数由调用隐式提供。

通常,方法的第一个参数称为 self。 这只不过是一个约定:名称 self 对 Python 绝对没有特殊含义。 但是请注意,如果不遵循约定,您的代码对于其他 Python 程序员的可读性可能会降低,并且还可以想象编写依赖于这种约定的类浏览器程序。

有关更多信息,请参阅有关类的 Python 文档教程

除了已经说明的所有其他原因之外,它还允许更轻松地访问被覆盖的方法; 你可以调用Class.some_method(inst)

一个有用的例子:

class C1(object):
    def __init__(self):
         print "C1 init"

class C2(C1):
    def __init__(self): #overrides C1.__init__
        print "C2 init"
        C1.__init__(self) #but we still want C1 to init the class too
>>> C2()
"C2 init"
"C1 init"

它的用法类似于Java 中this关键字的使用,即给出对当前对象的引用。

与 Java 或 C++ 不同,Python 不是为面向对象编程而构建的语言。

在 Python 中调用静态方法时,只需在其中编写一个带有常规参数的方法。

class Animal():
    def staticMethod():
        print "This is a static method"

然而,一个对象方法,它需要你创建一个变量,它是一个 Animal,在这种情况下,需要 self 参数

class Animal():
    def objectMethod(self):
        print "This is an object method which needs an instance of a class"

self 方法还用于引用类中的变量字段。

class Animal():
    #animalName made in constructor
    def Animal(self):
        self.animalName = "";


    def getAnimalName(self):
        return self.animalName

在这种情况下,self 指的是整个类的 animalName 变量。 记住:如果方法中有变量,self 将不起作用。 该变量仅在该方法运行时才存在。 为了定义字段(整个类的变量),您必须在类方法之外定义它们。

如果您对我所说的一个字都没有理解,那么请谷歌“面向对象编程”。 一旦你理解了这一点,你甚至不需要问那个问题:)。

首先,self 是一个传统名称,你可以用其他任何东西(连贯)来代替它。

它指的是对象本身,因此当您使用它时,您声明 .name 和 .age 是您要创建的 Student 对象(注意,不是 Student 类)的属性。

class Student:
    #called each time you create a new Student instance
    def __init__(self,name,age): #special method to initialize
        self.name=name
        self.age=age

    def __str__(self): #special method called for example when you use print
        return "Student %s is %s years old" %(self.name,self.age)

    def call(self, msg): #silly example for custom method
        return ("Hey, %s! "+msg) %self.name

#initializing two instances of the student class
bob=Student("Bob",20)
alice=Student("Alice",19)

#using them
print bob.name
print bob.age
print alice #this one only works if you define the __str__ method
print alice.call("Come here!") #notice you don't put a value for self

#you can modify attributes, like when alice ages
alice.age=20
print alice

代码在这里

它遵循 Python 禅宗“显式胜于隐式”。 它确实是对您的类对象的引用。 例如,在 Java 和 PHP 中,它被称为this

如果user_type_name是模型上的一个字段,您可以通过self.user_type_name访问它。

self是对对象本身的对象引用,因此它们是相同的。 Python 方法不会在对象本身的上下文中调用。 Python 中的self可用于处理自定义对象模型或其他东西。

我很惊讶没有人提到 Lua。 Lua 也使用 'self' 变量,但它可以省略但仍然使用。 C++ 对“this”做同样的事情。 我认为没有任何理由必须在每个函数中声明“self”,但您仍然应该能够像使用 lua 和 C++ 一样使用它。 对于一门以简洁而自豪的语言,它要求您声明 self 变量是很奇怪的。

这个论点的使用,通常称为self并不难理解,为什么它是必要的? 或者为什么明确提到它? 我想,对于大多数查找这个问题的用户来说,这是一个更大的问题,或者如果不是,他们在学习 python 时肯定会有同样的问题。 我建议他们阅读以下几篇博客:

1:使用自我解释

请注意,它不是关键字。

每个类方法(包括 init)的第一个参数始终是对当前类实例的引用。 按照惯例,这个参数总是命名为 self。 在init方法中,self指的是新创建的对象; 在其他类方法中,它指的是调用其方法的实例。 例如下面的代码与上面的代码相同。

2:为什么我们有这种方式,为什么我们不能像Java一样将它作为参数消除,而是有一个关键字

我想补充的另一件事是,可选的self参数允许我在类中声明静态方法,而不是编写self

代码示例:

class MyClass():
    def staticMethod():
        print "This is a static method"

    def objectMethod(self):
        print "This is an object method which needs an instance of a class, and that is what self refers to"

PS :这只适用于 Python 3.x。

在以前的版本中,您必须显式添加@staticmethod装饰器,否则self参数是强制性的。

看看下面这个例子,清楚地说明了self的目的

class Restaurant(object):  
    bankrupt = False

    def open_branch(self):
        if not self.bankrupt:
           print("branch opened")

#create instance1
>>> x = Restaurant()
>>> x.bankrupt
False

#create instance2
>>> y = Restaurant()
>>> y.bankrupt = True   
>>> y.bankrupt
True

>>> x.bankrupt
False  

self用于/需要区分实例。

资料来源: python 中的 self 变量解释 - Pythontips

是因为按照 python 的设计方式,替代方案几乎不起作用。 Python 旨在允许在隐式this (a-la Java/C++)或显式@ (a-la ruby​​)都不起作用的上下文中定义方法或函数。 让我们举一个使用 python 约定的显式方法的例子:

def fubar(x):
    self.x = x

class C:
    frob = fubar

现在fubar函数不起作用,因为它假设self是一个全局变量(并且在frob中也是如此)。 另一种方法是使用替换的全局范围(其中self是对象)执行方法。

隐含的方法是

def fubar(x)
    myX = x

class C:
    frob = fubar

这意味着myX将被解释为fubar (以及frob )中的局部变量。 这里的替代方法是使用替换的本地范围执行方法,该范围在调用之间保留,但这会消除方法局部变量的可能性。

不过目前的情况还不错:

 def fubar(self, x)
     self.x = x

 class C:
     frob = fubar

这里当作为方法调用时frob将通过self参数接收调用它的对象,并且fubar仍然可以使用对象作为参数调用并且工作相同(我认为它C.frob相同)。

__init__方法中,self 指的是新创建的对象; 在其他类方法中,它指的是调用其方法的实例。

self,作为一个名字,只是一个约定,你想怎么叫就怎么叫! 但是在使用它时,例如删除对象,您必须使用相同的名称: __del__(var) ,其中var__init__(var,[...])中使用

你也应该看看cls ,以获得更大的图景 这篇文章可能会有所帮助。

self 就像当前对象名称或 class 实例一样。

# Self explanation.


 class classname(object):

    def __init__(self,name):

        self.name=name
        # Self is acting as a replacement of object name.
        #self.name=object1.name

   def display(self):
      print("Name of the person is :",self.name)
      print("object name:",object1.name)


 object1=classname("Bucky")
 object2=classname("ford")

 object1.display()
 object2.display()

###### Output 
Name of the person is : Bucky
object name: Bucky
Name of the person is : ford
object name: Bucky

“self”关键字包含类的引用,是否使用它取决于您,但如果您注意到,每当您在 python 中创建新方法时,python 都会自动为您编写 self 关键字。 如果您进行一些研发,您会注意到,如果您在一个类中创建两个方法并尝试在另一个内部调用一个,除非您添加自我(类的引用),否则它不会识别方法。

class testA:
def __init__(self):
    print('ads')
def m1(self):
    print('method 1')
    self.m2()
def m2(self):
    print('method 2')

下面的代码会引发无法解决的引用错误。

class testA:
def __init__(self):
    print('ads')
def m1(self):
    print('method 1')
    m2()  #throws unresolvable reference error as class does not know if m2 exist in class scope
def m2(self):
    print('method 2')

现在让我们看看下面的例子

class testA:
def __init__(self):
    print('ads')
def m1(self):
    print('method 1')
def m2():
    print('method 2')

现在,当您创建类 testA 的对象时,您可以使用这样的类对象调用方法 m1(),因为方法 m1() 已包含 self 关键字

obj = testA()
obj.m1()

但是如果你想调用方法 m2(),因为它没有自引用,所以你可以直接使用类名调用 m2(),如下所示

testA.m2()

但是在实践中坚持使用 self 关键字,因为它还有其他好处,比如在内部创建全局变量等等。

self是不可避免的。

只有一个问题应该是隐含的还是显self的。 Guido van Rossum解决了这个问题,说self必须留下

那么self住在哪里呢?

如果我们只坚持函数式编程,我们就不需要self 一旦我们进入Python OOP ,我们就会在那里找到self

这是具有方法m1的典型用例class C

class C:
    def m1(self, arg):
        print(self, ' inside')
        pass

ci =C()
print(ci, ' outside')
ci.m1(None)
print(hex(id(ci))) # hex memory address

该程序将输出:

<__main__.C object at 0x000002B9D79C6CC0>  outside
<__main__.C object at 0x000002B9D79C6CC0>  inside
0x2b9d79c6cc0

所以self持有类实例的内存地址。 self的目的是保存实例方法的引用,并使我们能够显式访问该引用。


请注意,有三种不同类型的类方法:

  • 静态方法(阅读:函数),
  • 类方法,
  • 实例方法(提到)。

“自我”一词是指类的实例

class foo:
      def __init__(self, num1, num2):
             self.n1 = num1 #now in this it will make the perimeter num1 and num2 access across the whole class
             self.n2 = num2
      def add(self):
             return self.n1 + self.n2 # if we had not written self then if would throw an error that n1 and n2 is not defined and we have to include self in the function's perimeter to access it's variables

它是对类实例对象的显式引用。

文档中,

方法的特殊之处在于实例对象作为函数的第一个参数传递。 在我们的示例中,调用xf()完全等同于MyClass.f(x) 通常,使用包含 n 个参数的列表调用方法等效于使用参数列表调用相应的函数,该参数列表是通过在第一个参数之前插入方法的实例对象而创建的。

在此之前的相关片段,

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

x = MyClass()

我会说至少对于 Python,self 参数可以被认为是一个占位符。 看看这个:

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

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

在这种情况下,Self 和许多其他方法被用作存储名称值的方法。 然而,在那之后,我们使用 p1 将它分配给我们正在使用的类。 然后当我们打印它时,我们使用相同的 p1 关键字。

希望这对 Python 有所帮助!

我的小 2 美分

在这个 Person 类中,我们用 self 定义了init方法,有趣的是这里需要注意的是self和实例变量p的内存位置是相同的<__main__.Person object at 0x106a78fd0>

class Person:

    def __init__(self, name, age):
        self.name = name 
        self.age = age 

    def say_hi(self):
        print("the self is at:", self)
        print((f"hey there, my name is {self.name} and I am {self.age} years old"))

    def say_bye(self):
        print("the self is at:", self)
        print(f"good to see you {self.name}")

p = Person("john", 78)
print("the p is at",p)
p.say_hi()  
p.say_bye() 

所以如上所述,self 和 instance 变量都是同一个对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM