Python 这个词的目的是什么;自我';?

Python 这个词的目的是什么;自我';?,python,class,oop,self,Python,Class,Oop,Self,Python中的self单词的用途是什么?我理解它指的是从该类创建的特定对象,但我不明白为什么它需要显式地作为参数添加到每个函数中。举例来说,在Ruby中,我可以做到以下几点: class-myClass def myFunc(名称) @name=name 结束 结束 我很容易理解。但是,在Python中,我需要包含self: class myClass: def myFunc(self, name): self.name = name 有人能告诉我这件事吗?这不是我

Python中的
self
单词的用途是什么?我理解它指的是从该类创建的特定对象,但我不明白为什么它需要显式地作为参数添加到每个函数中。举例来说,在Ruby中,我可以做到以下几点:

class-myClass
def myFunc(名称)
@name=name
结束
结束
我很容易理解。但是,在Python中,我需要包含
self

class myClass:
    def myFunc(self, name):
        self.name = name

有人能告诉我这件事吗?这不是我在(公认有限的)经验中遇到的东西。

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

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


Python可能已经做了一些别的事情来区分普通名字和属性——像露比那样的特殊语法,或者需要像C++和java做的声明,或者可能有些不同的东西——但是它没有。Python完全是为了让事情变得明确,让事情变得显而易见,尽管它并不是在所有地方都这样做,但它确实在实例属性中这样做。这就是为什么分配给实例属性需要知道要分配给哪个实例,这就是为什么它需要
self。

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

以下摘录摘自:

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

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


有关更多信息,请参阅。

以及所有其他已说明的原因,它允许更容易地访问重写的方法;您可以调用
类。一些方法(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
我喜欢这个例子:

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: []

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

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\u global
的第一个参数可以重新用作
length\u new
中的
self
参数。如果没有显式的
self
,这是不可能的


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

v_instance.length()
内部转换为

Vector.length(v_instance)

很容易看出
self
的适用范围。实际上,您并没有用Python编写实例方法;您编写的是类方法,它必须将实例作为第一个参数。因此,您必须显式地将实例参数放置在某个位置。

我将用代码演示不使用类的情况:

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 )

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

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

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


如果
user\u type\u name
是您模型上的一个字段,您可以通过
self访问它。user\u type\u name

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

def methodA(self, arg1, arg2):
    # do something
ObjectA
就是这个类的一个实例

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

ClassA.methodA(ObjectA, arg1, arg2)

self
变量指的是对象本身。

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

self,作为一个名字,只是一个约定,你想怎么叫就怎么叫吧!但是当使用它时,例如删除对象时,您必须使用相同的名称:
\uu del_uuuuuuuuuu(var)
,其中
var
\uuuuu init_uuuuuuuuu(var,[…])

您也应该看看
cls
,以获得更大的图片
ClassA.methodA(ObjectA, arg1, arg2)
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  
class Animal():
    def staticMethod():
        print "This is a static method"
class Animal():
    def objectMethod(self):
        print "This is an object method which needs an instance of a class"
class Animal():
    #animalName made in constructor
    def Animal(self):
        self.animalName = "";


    def getAnimalName(self):
        return self.animalName
def fubar(x):
    self.x = x

class C:
    frob = fubar
def fubar(x)
    myX = x

class C:
    frob = fubar
 def fubar(self, x)
     self.x = x

 class C:
     frob = fubar
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
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"
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 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
class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)
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')
obj = testA()
obj.m1()
testA.m2()
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() 
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