想想这个例子:
class MyClass:
def func(self, name):
self.name = name
我知道self引用MyClass的特定实例。但是为什么func必须显式地包含self作为参数呢?为什么我们需要在方法的代码中使用self ?其他一些语言将其隐式化,或者使用特殊的语法。
有关设计决策的语言无关性考虑,请参见强制显式使用this/self指针的好处是什么?
要关闭OP省略方法的self形参并获得TypeError的调试问题,请使用TypeError: method()接受1个位置参数,但给出了2个。如果OP省略了self。在方法体中得到一个NameError,考虑如何在类中调用函数?
首先,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
代码在这里
我将用不使用类的代码演示:
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是隐式的还是显式的。
Guido van Rossum解决了这个问题说self必须留下来。
那么自我生活在哪里呢?
如果我们坚持函数式编程,我们就不需要self了。
一旦我们进入Python OOP,我们就会发现自己在那里。
下面是带有方法m1的典型用例类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的目的是保存实例方法的引用,并使我们能够显式地访问该引用。
注意有三种不同类型的类方法:
静态方法(读作:函数),
类方法,
实例方法(已提到)。
首先,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
代码在这里
我的小钱
在Person类中,我们用self定义了init方法,这里需要注意的有趣的事情是self和实例变量p的内存位置是相同的<__main__。位于0x106a78fd0>的Person对象
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和实例变量都是同一个对象。
当对象实例化时,对象本身被传递到self参数中。
因此,对象的数据被绑定到对象上。下面是一个示例,说明您可能希望如何可视化每个对象的数据。注意“self”是如何被对象名称替换的。我并不是说下面这个示例图是完全准确的,但希望它能在可视化self的使用方面起到一定的作用。
对象被传递到self参数中,这样对象就可以保存自己的数据。
Although this may not be wholly accurate, think of the process of instantiating an object like this: When an object is made it uses the class as a template for its own data and methods. Without passing it's own name into the self parameter, the attributes and methods in the class would remain as 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, they can all keep track of their own data and methods.
如下图所示: