self

What __init__ and self do on Python?

喜夏-厌秋 提交于 2019-11-26 03:12:38
问题 I\'m learning the Python programming language and I\'ve came across something I don\'t fully understand. In a method like: def method(self, blah): def __init__(?): .... .... What does self do? What is it meant to be? Is it mandatory? What does the __init__ method do? Why is it necessary? (etc.) I think they might be OOP constructs, but I don\'t know very much. 回答1: In this code: class A(object): def __init__(self): self.x = 'Hello' def method_a(self, foo): print self.x + ' ' + foo ... the

What is the purpose of the word 'self', in Python?

巧了我就是萌 提交于 2019-11-26 03:11:37
问题 What is the purpose of the self word in Python? I understand it refers to the specific object created from that class, but I can\'t see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this: class myClass def myFunc(name) @name = name end end Which I understand, quite easily. However in Python I need to include self : class myClass: def myFunc(self, name): self.name = name Can anyone talk me through this? It is not something I\'ve come

What is the difference between class and instance variables?

前提是你 提交于 2019-11-26 00:52:20
问题 What is the difference between class and instance variables in Python? class Complex: a = 1 and class Complex: def __init__(self): self.a = 1 Using the call: x = Complex().a in both cases assigns x to 1. A more in-depth answer about __init__() and self will be appreciated. 回答1: When you write a class block, you create class attributes (or class variables). All the names you assign in the class block, including methods you define with def become class attributes. After a class instance is

TypeError: method() takes 1 positional argument but 2 were given

被刻印的时光 ゝ 提交于 2019-11-26 00:16:33
问题 If I have a class ... class MyClass: def method(arg): print(arg) ... which I use to create an object ... my_object = MyClass() ... on which I call method(\"foo\") like so ... >>> my_object.method(\"foo\") Traceback (most recent call last): File \"<stdin>\", line 1, in <module> TypeError: method() takes exactly 1 positional argument (2 given) ... why does Python tell me I gave it two arguments, when I only gave one? 回答1: In Python, this: my_object.method("foo") ... is syntactic sugar, which

Why do you need explicitly have the “self” argument in a Python method?

一笑奈何 提交于 2019-11-25 23:53:25
问题 When defining a method on a class in Python, it looks something like this: class MyClass(object): def __init__(self, x, y): self.x = x self.y = y But in some other languages, such as C#, you have a reference to the object that the method is bound to with the \"this\" keyword without declaring it as an argument in the method prototype. Was this an intentional language design decision in Python or are there some implementation details that require the passing of \"self\" as an argument? 回答1: I