Difference in using self and this in python [duplicate] - python

This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 6 years ago.
Well, I am a newbie in Python and I am not able to understand the difference in using self and this keywords in Python.
This is the code that uses self as parameter :
class restaurant():
bankrupt = False
def open_branch(self):
if not self.bankrupt:
print("branch open")
x=restaurant()
print(x.bankrupt)
y=restaurant()
y.bankrupt=True
print(y.bankrupt)
And this is the code that uses this as parameter :
class restaurant():
bankrupt = False
def open_branch(this):
if not this.bankrupt:
print("branch open")
x=restaurant()
print(x.bankrupt)
y=restaurant()
y.bankrupt=True
print(y.bankrupt)
Both these approaches gave me the same output. So I m not able to understand why we use self when this solves our problem. Maybe my interpretation of self is wrong. I looked a lot of internet stuff but did not found anything relevant.
Can anyone please solve my issue.

It is mentioned in Python document:
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.

Using the name self is just a (strong) convention.
You are free to use any name instead, as long as you are constant.
It is highly recommended to use self though.
In general, Python gives you a lot of freedom doing things the way you like.
On the other hand, there are many conventions like how to name you variables (compare PEP8). In 99% of the cases it is best to adhere to this conventions. But if you a 1% case, you can do it differently. I have never seen a case for not using the name self though.
PEP8 recommends the use of self:
Always use self for the first argument to instance methods.

Related

Initialize Python class from arguments or same class [duplicate]

This question already has answers here:
What is a clean "pythonic" way to implement multiple constructors?
(15 answers)
How do I use method overloading in Python?
(17 answers)
Closed 3 years ago.
I'm trying to figure out a way to provide multiple ways to initialize a Python class, including from another instance of the class itself. If Python supported overloading, it would be as simple as this:
class Pet:
age =0
name=""
def __init__(self, a, n):
self.age =a
self.name=n
def __init__(self, p):
self.age =p.age
self.name=p.name
This way, you could initialize a Pet object by providing the members directly or initialize it from another Pet object. Unfortunately Python doesn't support overloading, so this isn't an option.
I tried searching for a solution, but the results were either unrelated or at best, only tangentially related and skirted around this specific case—which is strange because I'd bet cash-money that I'm not the first to run into this (I was hoping the similar-questions box would find something after I typed this up, but nope). 😕
Some of the answers to related, but different, questions I found were to use default arguments for __init__ or use isinstance, but I'm not sure how/if those could be adapted for this.
Is there a (practical) way to accomplish this?
(Yes, I could use pet2=Pet(pet1.age, pet1.name), but I mean, come, on. ¬_¬ I even considered making a separate initFromClass function, but that just makes things even messier than the previous expanded-argument solution.)

How methods work in python? [duplicate]

This question already has an answer here:
python string module vs str methods
(1 answer)
Closed 6 years ago.
I am new to programming therefore may sound idiotic. I am learning python where I am not able to understand how few methods like upper(), split() etc work.
I mean you directly use like below:
"ABC".upper() or "abc,xyz".split(",")
Or, you can first import string and then call these methods like below:
import string
string.upper("abc")
string.split("abc,xyz", ",")
What is the difference, and how would we import string module when we can achieve the same output without importing it.
Are there similar cases exist apart from string module?
In fact, one of the paradigm you can use in Python is the Object Oriented Programming, where you modify object state through "methods" like this: myobject.mymethod().
Syntactically, it means that the first argument of the method mymethod() is in fact the object itself. But, as Python want also to deal with other paradigms (functional programming, imperative programming, and so on), there is two syntactical ways to address this method.
One is simply as I mentioned before: myobject.mymethod(), and the other one is simply to consider that the first argument is the object itself: mymethod(myobject).
More precisely, you can realize that when you define by yourself a method because you have to specify the first argument by self which is a reference to the object itself like this:
def mymethod(self):
pass

Declaring functions in a class [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
python 'self' explained
I am a beginner in Python. I was going through the tutorials on Classes and Iterators when I had a doubt that I was unable to explain to myself. The program text below was a part of a class which calculates area.
def __init__(self,len,wid):
self.length=len
self.width=wid
def calculate_area(self)
return self.length*self.width
def print_area(self)
print 'Area='+str(self.calculate_area())
What I am unable to understand is why do the function's argument list have "self"? What is its role? Why are every variable resolved with "self"?
This is similar to this pointer in C++ (if you have come from C++ background)
Typical usage would be that the members of objects can be referenced by self in case if there is an ambiguity. e.g.
def calculate_area(self, length)
return self.length*self.width
Above length is an argument for calculate_area function.
if the object also has length member then it can be resolved by using self.length
Refer existing answer here:
What is the purpose of self?
I really don't know I'm too new on the Python world but I think that Python does not provide the this value as C# or Java do, so this is the mechanism that Python use to define itself in its classes.
Anyway you can see that you don't need to pass the self as parameter in the function call, because Python does for you.
This is my theory, but I'm also interested to know it so If anyone can say more about this, I think we will be very thankfull.
See you!

Why does Python require the "self" parameter? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
python ‘self’ explained
Why do you need explicitly have the “self” argument into a Python method?
Why does Python require the "self" parameter for methods?
For example def method_abc(self, arg1)
And is there ever a date that the need for it will be removed?
Python gives you the option of naming it something other than self, even though the standard is to name it self. Just as it gives you the option of using tabs for indents, even though the standard is to use spaces.
In other words, it's not just "assumed" because...
To give you naming flexibility
To make it clearer that something will be passed self (or not).

simulate private variables in python [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
private members in python
I've got few variables I really want to hide because they do not belong outside my class. Also all such non-documented variables render inheritance useless.
How do you hide such variables you don't want to show outside your object?
To clarify why I need private variables, first one example where inability to hide variables is just an inconvenience, then another that's really a problem:
class MyObject(object):
def __init__(self, length):
self.length = length
def __len__(self):
return length
item = MyObject(5)
item.length
len(item)
So I've got two ways to access 'length' of the item here. It's only an inconvenience and nothing horrible.
from wares import ImplementationSpecific
class MyThing(object):
def __init__(self):
self.__no_access_even_if_useful = ImplementationSpecific()
def restricted_access(self):
return self.__no_access_even_if_useful.mutable_value
thing = MyThing()
thing.restricted_access()
thing._MyThing__no_access_even_if_useful.something_useful_for_someone()
So say I want to change the implementation some day.. The chances are it'll break something unless I've really buried the implementation specifics.
I'll take it as anyone could program. That 'anyone' can find an useful thing from my implementation specifics and use it, even if I'd have strongly discouraged of doing so! It'd be much easier to just say: "no, it's not there, try something else."
Private variables is covered in the Python documentation:
9.6. Private Variables
“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.
Summary: use an underscore before the name.
From the Python docs:
“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

Categories

Resources