想想这个例子:
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,考虑如何在类中调用函数?
我想说,至少对于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在这里,还有很多其他的被用作存储name值的方法。然而,在此之后,我们使用p1将其分配给我们正在使用的类。然后当我们打印它时,我们使用相同的p1关键字。
希望这对Python有所帮助!
与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的Python文档:
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.
有关更多信息,请参阅Python类文档教程。
首先,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
代码在这里