python init self,Python中“ self”和“ __init__”表达式的含义是什么?

I don't understand what these are used for, particularly the self argument? Could some please explain this to me and why on earth you would want to pass this in?

Also, I've always thought __init__ was for 'initialisation', but it didn't occur to me that I've never had to put anything in here before. Could someone give me an easy example?

edit: i just get so confused everytime i see self being passed into a function, or something of the like.

解决方案

self is the object you're calling the method on. It's a bit like this in Java.

__init__ is called on each object when it is created to initialise it. It's like the constructor in Java.

So you would use __init__ whenever you wanted to set any attributes - member variables in Java - of the object when it was created. If you're happy with an "empty" object you don't need an __init__ method but if you want to create an object with arguments you'll need one.

An example would be:

class StackOverflowUser:

def __init__(self, name, userid, rep):

self.name = name

self.userid = userid

self.rep = rep

dave = StackOverflowUser("Dave Webb",3171,500)

We can then look at the object we've created:

>>> dave.rep

500

>>> dave.name

'Dave Webb'

So we can see __init__ is passed the arguments we gave to the constructor along with self, which is the reference to the object that has been created. We then use self when we process the arguments and update the object appropriately.

There is the question of why Python has self when other languages don't need it. According to the Python FAQ:

Why must 'self' be used explicitly in method definitions and calls?

First, it's more obvious that you are using a method or instance attribute instead of a local variable...

Second, it means that no special syntax is necessary if you want to explicitly reference or call the method from a particular class...

Finally, for instance variables it solves a syntactic problem with assignment: since local variables in Python are (by definition!) those variables to which a value assigned in a function body (and that aren't explicitly declared global), there has to be some way to tell the interpreter that an assignment was meant to assign to an instance variable instead of to a local variable, and it should preferably be syntactic (for efficiency reasons)...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值