Python, __init__ and self confusion

前端 未结 5 543
别跟我提以往
别跟我提以往 2021-01-20 02:48

Alright, so I was taking a look at some source when I came across this:

>>> def __parse(self, filename):
...         \"parse ID3v1.0 tags from MP3 f         


        
5条回答
  •  庸人自扰
    2021-01-20 03:15

    Looks like you're a bit confused about classes and object-oriented programming. The 'self' thing is one of the gotchas in python for people coming from other programming languages. IMO the official tutorial doesn't handle it too well. This tutorial seems quite good.

    If you've ever learnt java, self in python is very similar to this in java. The difference is that python requires you to list self as the first argument to every function in a class definition.

    If python is your first programming language (or your first object-oriented language), you could remember this as a simple rule-of-thumb: if you're defining a function that's part of a class, you need to include self as the first argument. If you're defining a function that's not part of a class, you shouldn't include self in the arguments. You can't take a class function and make it stand-alone without doing some (or possibly a lot of) extra coding. Finally, never include self as an argument when calling a function.

    There are exceptions to those rules, but they're not worth worrying about now.

提交回复
热议问题