“自我”参数的目的是什么?为什么需要它?

发布于 2025-02-11 11:25:57 字数 661 浏览 4 评论 0 原文

考虑此示例:

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

我知道 self 是指 myclass 的特定实例。但是,为什么 func 明确将 self 作为参数?为什么我们需要在方法的代码中使用 self ?其他一些语言使这种隐式或使用特殊语法。


对于A 语言 - agnostic 考虑设计决定的考虑指针强制性显式?。

关闭调试问题其中op省略了 self 一种方法的参数并获得了 type> type> typeerror ,使用 typeError:typeError:method()取1个位置参数,但给出了2个,但 。如果在该方法的正文中省略了 self。我可以在类中调用功能吗?。

Consider this example:

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

I know that self refers to the specific instance of MyClass. But why must func explicitly include self as a parameter? Why do we need to use self in the method's code? Some other languages make this implicit, or use special syntax instead.


For a language-agnostic consideration of the design decision, see What is the advantage of having this/self pointer mandatory explicit?.

To close debugging questions where OP omitted a self parameter for a method and got a TypeError, use TypeError: method() takes 1 positional argument but 2 were given instead. If OP omitted self. in the body of the method and got a NameError, consider How can I call a function within a class?.

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

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

发布评论

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

评论(27

呆橘 2025-02-18 11:25:57

您需要使用 self。的原因是因为Python不使用特殊语法来参考实例属性。 Python决定以一种使该方法属于 自动传递的实例的方式,而不是自动传递的方法:方法的第一个参数是实例被称为。这使方法与函数完全相同,并将实际名称留给您(尽管 self 是惯例,当您使用其他内容时,人们通常会向您皱眉。)> self 对代码不是特别的,它只是另一个对象。

Python本可以做其他事情以将正常名称与属性区分开 - 像Ruby一样的特殊语法,或者需要C ++和Java之类的声明,或者可能更不同 - 但事实并非如此。 Python的全部是使事物明确的,使它显而易见,尽管它并不完全在任何地方做到这一点,但它确实做到了,例如属性。这就是为什么分配给实例属性需要知道要分配的实例的原因,这就是为什么它需要 self。

The reason you need to use self. is because Python does not use special syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (although self is the convention, and people will generally frown at you when you use something else.) self is not special to the code, it's just another object.

Python could have done something else to distinguish normal names from attributes -- special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different -- but it didn't. Python's all for making things explicit, making it obvious what's what, and although it doesn't do it entirely everywhere, it does do it for instance attributes. That's why assigning to an instance attribute needs to know what instance to assign to, and that's why it needs self..

命比纸薄 2025-02-18 11:25:57

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

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

objecta 是此类的实例。

现在,当调用 objecta.methoda(arg1,arg2)时,python内部将其转换为:

ClassA.methodA(objectA, arg1, arg2)

self 变量涉及对象本身。

Let's say you have a class ClassA which contains a method methodA defined as:

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

and objectA is an instance of this class.

Now when objectA.methodA(arg1, arg2) is called, python internally converts it for you as:

ClassA.methodA(objectA, arg1, arg2)

The self variable refers to the object itself.

心碎的声音 2025-02-18 11:25:57

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

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的第一个参数,可以作为 self 参数重复使用 length_new 。没有明确的 self ,这将是不可能的。


理解对明确 self 的需求的另一种方法是查看python添加一些句法糖。当您牢记时,基本上,像

v_instance.length()

内部转换为

Vector.length(v_instance)

内部的呼叫很容易看到 self 适合所在的位置。您实际上并未在Python中编写实例方法。您写的是类方法,必须将实例作为第一个参数。因此,您必须明确将实例参数放置在某个地方。

Let’s take a simple vector class:

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

We want to have a method which calculates the length. What would it look like if we wanted to define it inside the class?

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

What should it look like when we were to define it as a global method/function?

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

So the whole structure stays the same. How can me make use of this? If we assume for a moment that we hadn’t written a length method for our Vector class, we could do this:

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

This works because the first parameter of length_global, can be re-used as the self parameter in length_new. This would not be possible without an explicit self.


Another way of understanding the need for the explicit self is to see where Python adds some syntactical sugar. When you keep in mind, that basically, a call like

v_instance.length()

is internally transformed to

Vector.length(v_instance)

it is easy to see where the self fits in. You don't actually write instance methods in Python; what you write is class methods which must take an instance as a first parameter. And therefore, you’ll have to place the instance parameter somewhere explicitly.

南城追梦 2025-02-18 11:25:57

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

“在此处输入图像说明”

因此,对象的数据绑定到对象。以下是一个人想如何可视化每个对象数据可能看起来的示例。注意 self 如何替换为对象的名称。我并不是说下面的示例图是完全准确的,但是希望它可以帮助一个人可视化 self 的使用。

“在此处输入图像说明”

将对象传递到 self parameter中,以便对象可以保持保持其自己的数据。

尽管这可能不是完全准确的,但请考虑实例化的过程(创建分配内部值)这样的对象:当制作对象时,对象将类用作其模板(对象的)自己的数据和方法。如果不将对象自己的变量名称传递到 self 参数中,则类中的属性和方法将是一个常规模板,并且不会引用(属于)对象。因此,通过将对象的名称传递到 self 参数中,这意味着,如果从一个类实例化了100个对象,那么100个对象中的每个对象都可以跟踪其(每个对象)自己的数据和方法。

摘要:类是一般的(不是超特定的)模板,一个新创建的对象可以将其自己的特定数据传递到(不一定会影响可以从同一类创建的对象的情况下必然),允许使用较少的复制代码,其目的是创建许多具有相同模式的对象。 self 用于指定A 特定对象的数据应使用而不是其他数据。

请参阅下面的插图:

“在此处输入图像说明”

When objects are instantiated, the object itself is passed into the self parameter.

enter image description here

Because of this, the object’s data is bound to the object. Below is an example of how one might like to visualize what each object’s data might look. Notice how self is replaced with the object's name. I'm not saying this example diagram below is wholly accurate, but it will hopefully help one visualize the use of self.

enter image description here

The Object is passed into the self parameter so that the object can keep hold of its own data.

Although this may not be wholly accurate, think of the process of instantiating (creating and assigning internal values) an object like this: When an object is made, the object uses the class as a template for its (the object's) own data and methods. Without passing the object's own variable name into the self parameter, the attributes and methods in the class would remain a general template and would not be referenced to (belong to) the object. So, by passing the object's name into the self parameter, it means that if 100 objects are instantiated from the one class, each of the 100 objects can keep track of its (each object's) own data and methods.

Summary: Classes are general (not ultra-specific) templates that a newly created object can pass its own specific data into (without necessarily affecting the rest of the objects that could be created from the same class), allowing for less copy-pasted code that serves the purpose of creating many objects that have the same patterns. self is for specifying that a specific object's data should be used instead of some other data.

See the illustration below:

enter image description here

紫轩蝶泪 2025-02-18 11:25:57

我喜欢这个示例:

class A: 
    foo = []

a, b = A(), A()
a.foo.append(5)

b.foo  # [5]
class A: 
    def __init__(self): 
        self.foo = []

a, b = A(), A()
a.foo.append(5)

b.foo  # []

I like this example:

class A: 
    foo = []

a, b = A(), A()
a.foo.append(5)

b.foo  # [5]
class A: 
    def __init__(self): 
        self.foo = []

a, b = A(), A()
a.foo.append(5)

b.foo  # []
苦妄 2025-02-18 11:25:57

我将用代码证明不使用类:

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 )

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

I will demonstrate with code that does not use classes:

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'

Classes are just a way to avoid passing in this "state" thing all the time (and other nice things like initializing, class composition, the rarely-needed metaclasses, and supporting custom methods to override operators).

Now let's demonstrate the above code using the built-in python class machinery, to show how it's basically the same thing.

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 )

[migrated my answer from duplicate closed question]

拥抱影子 2025-02-18 11:25:57

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

与Modula-3中一样,没有用于从其方法引用对象成员的速记(在Python中):方法函数是用代表对象的明确的第一个参数声明的,该函数由呼叫。

通常,方法的第一个论点称为自我。这无非是一种惯例:“自我”这个名字绝对没有特殊的意义。但是,请注意,通过不遵循《惯例》,您的代码可能不太对其他Python程序员读取,并且也可以想象,可以编写依赖此类约定的类浏览器程序。

有关更多信息,请参见 python文档教程

The following excerpts are from the Python documentation about self:

As in Modula-3, there are no shorthands [in Python] for referencing the object’s members from its methods: the method function is declared with an explicit first argument representing the object, which is provided implicitly by the call.

Often, the first argument of a method is called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers, and it is also conceivable that a class browser program might be written that relies upon such a convention.

For more information, see the Python documentation tutorial on classes.

一身骄傲 2025-02-18 11:25:57

除了所有已经说明的其他原因外,它还可以更轻松地访问覆盖方法。您可以调用 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"

As well as all the other reasons already stated, it allows for easier access to overridden methods; you can call Class.some_method(inst).

An example of where it’s useful:

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"
稀香 2025-02-18 11:25:57

它的使用类似于使用在Java中的关键字,即为当前对象提供引用。

Its use is similar to the use of this keyword in Java, i.e. to give a reference to the current object.

少钕鈤記 2025-02-18 11:25:57

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

首先,方法属于整个类( static方法)或类(对象方法)的对象(实例)。

在python中调用静态方法时,只需写入其中带有常规参数的方法。

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

但是,需要您制作对象的对象(IE,实例)方法(即在这种情况下是一种动物),需要 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 指的是整个类 的动物名称变量。请记住:如果您在方法中有一个新的变量创建(称为局部变量),则 self 将无法使用。该变量仅在该方法运行时存在。要定义字段(整个类的变量),您必须在类方法之外定义它们。

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

Python is not a language built for Object Oriented Programming, unlike Java or C++.

First off, methods belong to either an entire class (static method) or an object (instance) of the class (object method).

When calling a static method in Python, one simply writes a method with regular arguments inside it.

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

However, an object (i.e., instance) method, which requires you to make an object (i.e. instance, an Animal in this case), needs the self argument.

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

The self method is also used to refer to a variable field within the class.

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

    def getAnimalName(self):
        return self.animalName

In this case, self is referring to the animalName variable of the entire class. REMEMBER: If you have a new variable created within a method (called a local variable), self will not work. That variable exists only while that method is running. For defining fields (the variables of the entire class), you have to define them OUTSIDE the class methods.

If you don't understand a single word of what I am saying, then Google "Object Oriented Programming." Once you understand this, you won't even need to ask that question :).

沉睡月亮 2025-02-18 11:25:57

首先,自我是一个传统的名称,您可以将其他任何东西(连贯)代替。

它指的是对象本身,因此,当您使用该对象时,您会声明.NAME和.AGE是您将要创建的学生对象的属性(注意,而不是学生班的)。

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

代码在这里

First of all, self is a conventional name, you could put anything else (being coherent) in its stead.

It refers to the object itself, so when you are using it, you are declaring that .name and .age are properties of the Student objects (note, not of the Student class) you are going to create.

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

Code is here

无戏配角 2025-02-18 11:25:57

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

self is an object reference to the object itself, therefore, they are same.
Python methods are not called in the context of the object itself.
self in Python may be used to deal with custom object models or something.

在巴黎塔顶看东京樱花 2025-02-18 11:25:57

在那里遵循Python Zen“明确胜于隐式”。这确实是对您的班级对象的参考。例如,在Java和PHP中,称为 this

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

It’s there to follow the Python zen “explicit is better than implicit”. It’s indeed a reference to your class object. In Java and PHP, for example, it's called this.

If user_type_name is a field on your model you access it by self.user_type_name.

二手情话 2025-02-18 11:25:57

我很惊讶没有人提出卢阿。 LUA还使用“自我”变量,但是可以省略但仍使用。 C ++对“ this”做同样的事情。我没有任何理由必须在每个功能中声明“自我”,但是您仍然应该能够像使用LUA和C ++一样使用它。对于一种以简短的态度而自豪的语言是奇怪的是,它要求您声明自我变量。

I'm surprised nobody has brought up Lua. Lua also uses the 'self' variable however it can be omitted but still used. C++ does the same with 'this'. I don't see any reason to have to declare 'self' in each function but you should still be able to use it just like you can with lua and C++. For a language that prides itself on being brief it's odd that it requires you to declare the self variable.

往事随风而去 2025-02-18 11:25:57

请查看以下示例,该示例清楚地说明了 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中的自我变量a>

Take a look at the following example, which clearly explains the purpose of 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 is used/needed to distinguish between instances.

Source: self variable in python explained - Pythontips

酒几许 2025-02-18 11:25:57

常规称为 self 的参数的使用并不那么难以理解,为什么它是必要的?还是为什么明确提及它?我想,对于大多数查找这个问题的用户来说,这是一个更大的问题,或者如果不是这样,他们肯定会有同样的问题,因为他们继续学习python。我建议他们阅读这对博客:

1 :使用自我解释

请注意,这不是关键字。

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

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 decorator,否则 self 参数是必不可少的。

The use of the argument, conventionally called self isn't as hard to understand, as is why is it necessary? Or as to why explicitly mention it? That, I suppose, is a bigger question for most users who look up this question, or if it is not, they will certainly have the same question as they move forward learning python. I recommend them to read these couple of blogs:

1: Use of self explained

Note that it is not a keyword.

The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self. In the init method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. For example the below code is the same as the above code.

2: Why do we have it this way and why can we not eliminate it as an argument, like Java, and have a keyword instead

Another thing I would like to add is, an optional self argument allows me to declare static methods inside a class, by not writing self.

Code examples:

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:This works only in Python 3.x.

In previous versions, you have to explicitly add @staticmethod decorator, otherwise self argument is obligatory.

强辩 2025-02-18 11:25:57

是因为根据Python设计的方式,替代方案几乎无效。 python旨在允许在隐式 this (a-la java/c ++)或explicit @(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 fubar 仍然可以将对象称为参数,并且可以使用相同的工作( IS c.frob 我认为)。

Is because by the way python is designed the alternatives would hardly work. Python is designed to allow methods or functions to be defined in a context where both implicit this (a-la Java/C++) or explicit @ (a-la ruby) wouldn't work. Let's have an example with the explicit approach with python conventions:

def fubar(x):
    self.x = x

class C:
    frob = fubar

Now the fubar function wouldn't work since it would assume that self is a global variable (and in frob as well). The alternative would be to execute method's with a replaced global scope (where self is the object).

The implicit approach would be

def fubar(x)
    myX = x

class C:
    frob = fubar

This would mean that myX would be interpreted as a local variable in fubar (and in frob as well). The alternative here would be to execute methods with a replaced local scope which is retained between calls, but that would remove the posibility of method local variables.

However the current situation works out well:

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

 class C:
     frob = fubar

here when called as a method frob will receive the object on which it's called via the self parameter, and fubar can still be called with an object as parameter and work the same (it is the same as C.frob I think).

時窥 2025-02-18 11:25:57

__ Init __ 方法中,自我指的是新创建的对象;在其他类方法中,它是指调用方法的实例。

self as hif as 只是惯例 ,请按照自己的意愿称呼它!但是在使用它时,例如要删除对象,您必须使用相同的名称: __ del __(var),其中 var __ init __ Init __( var,[...])

您也应该查看 cls ,以使 更大的图片 。此 POST 可能会有所帮助。

In the __init__ method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called.

self, as a name, is just a convention, call it as you want ! but when using it, for example to delete the object, you have to use the same name: __del__(var), where var was used in the __init__(var,[...])

You should take a look at cls too, to have the bigger picture. This post could be helpful.

鹿港巷口少年归 2025-02-18 11:25:57

自我就像当前对象名称或类的实例一样。

# 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 is acting as like current object name or instance of 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
栀子花开つ 2025-02-18 11:25:57

“ self”关键字包含类的参考,如果您想使用或不使用它,则可以通过它,但如果您注意到,每当您在Python中创建新方法时,Python都会自动为您编写自关键字。如果您做一些R& d,您会注意到,如果您在班级中创建两个方法并尝试在另一个中调用一个方法,则除非添加自我(班级的引用),否则它将无法识别方法。

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()已包含自关键字

obj = testA()
obj.m1()

,但是如果您要调用方法m2(),因为没有自我参考,因此您可以使用以下类似的类名来直接调用M2(),

testA.m2()

但要练习以自我关键字来依靠其他好处,因为它还有其他好处,例如在内部创建全局变量等。

"self" keyword holds the reference of class and it is upto you if you want to use it or not but if you notice, whenever you create a new method in python, python automatically write self keyword for you. If you do some R&D, you will notice that if you create say two methods in a class and try to call one inside another, it does not recognize method unless you add self (reference of class).

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

Below code throws unresolvable reference error.

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')

Now let see below example

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

Now when you create object of class testA, you can call method m1() using class object like this as method m1() has included self keyword

obj = testA()
obj.m1()

But if you want to call method m2(), because is has no self reference so you can call m2() directly using class name like below

testA.m2()

But keep in practice to live with self keyword as there are other benefits too of it like creating global variable inside and so on.

北方。的韩爷 2025-02-18 11:25:57

self 是不可避免的。

只有一个问题应该 self 是隐式或明确的。
guido van rossum 解决了这个问题://neopythonic.blogspot.com/2008/10/why-explitic-self-self-has-to-stay.html“ rel =“ nofollow noreferrer”> self 必须保持。

那么, self live的何处?

如果我们只坚持功能编程,我们将不需要 self
输入 python oop 后,我们在那里找到 self

这是典型的用例类C 与方法 m1

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

So self 保留类实例的内存地址。
self 的目的是保留实例方法的参考参考。


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

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

self is inevitable.

There was just a question should self be implicit or explicit.
Guido van Rossum resolved this question saying self has to stay.

So where the self live?

If we would just stick to functional programming we would not need self.
Once we enter the Python OOP we find self there.

Here is the typical use case class C with the method m1

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

This program will output:

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

So self holds the memory address of the class instance.
The purpose of self would be to hold the reference for instance methods and for us to have explicit access to that reference.


Note there are three different types of class methods:

  • static methods (read: functions),
  • class methods,
  • instance methods (mentioned).
逆夏时光 2025-02-18 11:25:57

“自我”一词是指班级的实例

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

The word 'self' refers to instance of a class

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
指尖凝香 2025-02-18 11:25:57

这是对类实例对象的明确引用。

it's an explicit reference to the class instance object.

誰認得朕 2025-02-18 11:25:57

来自 docs ,,

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

在此之前,相关片段,

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

    def f(self):
        return 'hello world'

x = myClass()

from the docs,

the special thing about methods is that the instance object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s instance object before the first argument.

preceding this the related snippet,

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

    def f(self):
        return 'hello world'

x = MyClass()

往日 2025-02-18 11:25:57

我在这个班级的人中的小2美分

,我们在这里定义了 init 方法,在这里要注意的是 self 和实例变量的记忆位置 p 是相同的&lt; __ main __。在0x106a78fd0&gt; 上的人对象

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和实例变量都是同一对象。

my little 2 cents

In this class Person, we defined out init method with the self and interesting thing to notice here is the memory location of both the self and instance variable p is same <__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() 

so as explained in above, both self and instance variable are same object.

新人笑 2025-02-18 11:25:57

使用 self Python的设计决定,从语言设计的角度来看,并非严格强制强制强制,以使实例对象明确并区分实例变量与局部变量。您可以想到 self 始终在那里隐含的替代方案,因为Guido的Blogpost回应了:

class MyClass:
    def __init__(n):  # implicit self
        self.n = n  

    def print_n():
        print(self.n)

这违背了Python的咒语“显式比隐含更好”。或使用特殊的语法来参考ruby中的实例变量。但是,Python试图将语法字符保持在最低限度(如今,它正在添加更多语法,例如sistizitment表达式和类型提示)。这在功能上与隐式 self 相同,除非您不将 self 像隐藏的变量一样。

class MyClass:
    def __init__(n):
        @n = n

    def print_n():
        print(@n)

另一个替代方法是C ++样式语法,使用隐式和明确的类似数据级的声明(相对较新):

class MyClass:
    n: int

    def __init__(n):
        this.n = n 

    def print_n():
        print(n)  # default to instance variable

仅用于从实例变量中删除本地变量。如果没有混淆,则使用“类范围” n 。我认为这比在任何地方使用显式 self 更干净,但是您需要跟踪什么和ISN' t实例状态

Using self is a design decision by python, not strictly mandatory from a language design point of view, to make explicit the instance object and distinguish instance variables from local variables. You could conceive of an alternative where self is always implicitly there, as Guido's blogpost responds to:

class MyClass:
    def __init__(n):  # implicit self
        self.n = n  

    def print_n():
        print(self.n)

This goes against python's mantra of "explicit is better than implicit". Or use special syntax to refer to instance variables as in Ruby. However Python tries to keep syntax characters to a minimum (nowadays it is adding more syntax, like assignment expressions and type hinting). This is functionally the same as implicit self, except you don't treat self like a hidden variable.

class MyClass:
    def __init__(n):
        @n = n

    def print_n():
        print(@n)

Another alternative is C++ style syntax, using implicit this and explicit dataclass-like declarations (which are relatively new):

class MyClass:
    n: int

    def __init__(n):
        this.n = n 

    def print_n():
        print(n)  # default to instance variable

this is only used to disambiguate the local variable from the instance variable. If there is no confusion, the "class scope" n is used. I think this is cleaner than using explicit self everywhere, but you need to keep track of what is and isn't instance state.

情深缘浅 2025-02-18 11:25:57

我至少要说python,可以将自我参数视为占位符。
看看这一点:

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

p1 = Person("John", 36)

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

在这种情况下,自我,许多其他人被用作说出名称值的方法。但是,在那之后,我们使用P1将其分配给我们使用的类。然后,当我们打印它时,我们使用相同的P1关键字。

希望这对Python有帮助!

I would say for Python at least, the self parameter can be thought of as a placeholder.
Take a look at this:

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

p1 = Person("John", 36)

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

Self in this case and a lot of others was used as a method to say store the name value. However, after that, we use the p1 to assign it to the class we're using. Then when we print it we use the same p1 keyword.

Hope this helps for Python!

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