Declaring functions in a class [duplicate] - python

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!

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.)

Difference in using self and this in python [duplicate]

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.

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

Python3 - When exactly do you need to prepend "self._" to variable declarations within class methods? [duplicate]

This question already has answers here:
Does it make a difference using self for a temporary variable in a Python method?
(4 answers)
Closed 7 years ago.
Sorry, this is a really basic question, but I am just wondering when it is necessary to prepend self._ to variable declarations within methods? Every time I declare a variable within a method should I declare it with self._ included? Is there any situation where I should not do this?
Which of these methods would be valid for example (for some hypothetical class):
def thing_counter(self, thing):
length_of_thing = len(thing)
return length_of_thing
OR
def thing_counter(self, thing):
self._length_of_thing = len(thing)
return self._length_of_thing
Both work, but which would be strictly correct?
I know that a variable declaration is not really needed here, I am just trying to use a simple example.
Cheers!
Both work equally.
In the first version, length_of_thing will be created inside the function, and the return will return a copy to the caller. length_of_thing itself will not exist anymore after the return.
In the second one, self._length_of_thing will be created, not inside the function, but inside the instance of the class. The result is that it will be visible to all other methods. And the return still returns a copy.
So possibly this version uses a little more memory, as the variable self._length_of_thing remains alive till the instance of the class is destroyed.

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).

Categories

Resources