Python assignment and OO

Asked

Viewed 447 times

3

Studying about object orientation in Python I was told that a difference of such language in the instance and assignment of a class is, when we do

Darth = Pessoa ( 'Darth Vader' )

The name / surname Darth is being assigned the class and not the other way around, which I believe is the commonly inferred by developers since the other way around is valid for other items as variables of primitive language types int, float, bool, str...

In the video material I found nothing beyond that was said (that’s why I didn’t leave the same as source on this question), so I would like to know if this actually occurs, and if it occurs what it interferes with development and what we should know about it so that we do not make mistakes?

How it works to assign the object a nickname and not the object to the nickname?

  • 2

    Set the opposite. Assign a class to an object? That’s impossible. I can already say that the material looks bad. These question phrases don’t make much sense. como funciona atribuir ao objeto um apelido e não o objeto ao apelido What are you talking about? What is nickname for you?

  • The ' contrario ' : the idea that the object is assigned to variable / name / nickname / symbol ... as you prefer to call

2 answers

5


Reliable sources

First start by saying that it is common for video lessons to be bad, in general they are made by voluntary people who understand nothing of the subject that can not evaluate itself in an effect Dunning-Krugger and teach wrong. The problem is that the person who does not know yet can not discern what is good or not. Of course there’s bad stuff that’s not video and there are good classes like that, usually paid and cured somewhere that needs credibility. Even what is well recommended can be bad because in general the people who recommend do not know how to evaluate if it is good, so consider good what is actually not.

Object orientation

You need to understand that object orientation is not something magical that solves programming problems on its own. It’s a paradigm that helps certain problems, not all problems. It is not a programming language. It is a secondary paradigm in all languages mainstream. People talk about it so much in fashion. People want to be fashionable, follow the herd and why they want their codes to be OO, even when they don’t need it or even it is. Often we see questions here with tag who doesn’t have a comma on OOP. One just wants to be in that popular group. And this is one of the reasons people want to learn OOP. Too bad they don’t want to learn where to use the paradigm and where not to use it. They don’t want to learn what the actual paradigm is.

It is much more important to understand general fundamentals of computation than OOP. Of course at a certain point you need OOP too, but you need to learn right and you can’t follow cake recipes.

I even understand that some people think that object orientation is playing with words. If that’s it, it serves for nothing. It has to have a practical effect.

Your problem

The line Darth = Pessoa('Darth Vader') is calling a class builder Pessoa passing as argument a text with a name of a person and this object is being assigned to a variable. Well, I don’t really know if it’s a constructor. Python leaves the syntax ambiguous and could just be a normal function, but everything indicates that it’s a constructor. Anything you can imagine beyond that is speculation or something nonexistent.

He will generate an object just like he would with a int, float, bool, etc. All this is object too. They are usually objects by value, which some people like to call primitive. You create instances of these types as well. But in Python they are not, in Python everything is in heap and everything is reference. Still they have semantics of types by value.

Some people call string primitive, which I don’t know if it is, depends on the concept of what a primitive is. If it’s something the computer can process directly, then it’s not primitive. If it is something that language gives a special treatment, then it is possible depending on the language.

Object composition

In Python the only way to create an object composed of other objects within a specific format is with the class. You can also create collections of data, but that serves another purpose, I won’t go into detail here. These classes are always by reference, as are collections such as lists and dictionaries, for example. Other types are by reference, but have value semantics, and this is very important. They have identity and are immutable.

Contrary to what many people think a class is just a way of structuring, of planning an object. This is not object orientation. It’s creating a model for an object, but not oriented to it. A language is not known to be object-oriented, although you can program in it with difficulty, and you create objects in it in the same way.

So the code presented in the question has zero object orientation. If they taught like this, they taught wrong.

Now, the way the class was created can be object-oriented. You need to see if the implementation detail is encapsulated, if there is an abstraction, if the object can be made up of another object, if it can take the form of another object. If you follow all this correctly it is likely that you will have to adopt certain standards to accomplish certain tasks, provide certain mechanisms and achieve certain objectives. If you follow a part maybe it’s a modular code that many think is object-oriented.

As an effect of encapsulation there must be a constructor, it begins to be somewhat object oriented.

But what is there doesn’t matter if it’s OO or not. It’s a very simple line that doesn’t mean much.

Variables

I may be wrong, but it seems to me you still don’t understand what is variable, which is the basics of the basics. Of course, a lot of people who have been programming for years don’t know either. What bothers me is that people don’t know what a brick is for and they want to make art in construction. That’s wrong. Before learning an advanced finishing technique need to make everything stand up right.

I’m not sure what a nickname is there. Is it the variable? A variable cannot be assigned to an object, in any paradigm, that doesn’t make sense. You may have seen a play on words. If the result is exactly the same, it’s all the same. It may be said that in orientation the object is given a name for an object and in another paradigm an object is placed in a name, which is exactly the same for all effects. Or almost.

Variable is name for a data storage location. But variable is not every object that is in memory. Variable stores basic data, in general by value or at least with this semantics. When it does not store something by value it only stores the reference to another object.

So it’s often said that variables are boxes. And they are, that’s where data goes into it. But understand that the variable is the name for the storage location. It doesn’t exist in the concrete, it exists only in your code. In every variable there is a data, which can be the identity of the object (by value) or not (by reference). In Python every object is by reference, so every variable is a reference. You will never have the object itself in it.

When there is a reference there is a box that points to another box that is the object that matters. This other box is not a variable ever, at least in every implementation I know. In Python every variable has these two boxes and one of them has a name that I think is what you’re calling a nickname.

It is not even possible to assign an object to the nickname, assign a value to a variable, where it will have a storage location for the reference and another for the object identity.

Completion

In the other question:

makes more sense to say that the variable is assigned to an object and not the other way around, ie the object is created before the assignment

It turns out that the variable is created before, it already exists there in the code and in memory before the object exists, the object is created and then assigned in the variable that already exists. So that sentence makes no sense.

The multiplication attempt by an instance of Foo, raises an exception, but the side effect of the id of Foo proves that a second instance was created before the multiplication attempt.

That just proves the guy Foo cannot do a multiplication. It makes no sense.

Since variables are only labels, nothing prevents an object from having multiple labels assigned to it

Variables, in Python, are always references so they can always point to the same object. That’s it. Na has to do with labels. The label is the name, but not the place of storage.

There are other confusions there. I even understand what was the intention of the answer, but the lack of the foundation ends up creating more confusion.

The AP must have seen one of them. Maybe they tried to simplify the understanding, which is good, but the result was that they taught wrong.

Other than that the question is very broad, what else you have to know about the topic is... everything on the subject, there is no way to skip parts, information half causes more problem that helps.

See also, even if it is another language: Memory allocation in C# - Value types and reference types.

  • 2

    pity that they do not want to learn where to use the paradigm and where not to use - It reminded me of the time in school when students learn how to solve high school equations but don’t know where their applicability is or how to apply them to real problems. It seems that sometimes only "learn" to pass the tests. And this seems to happen a lot in relation to the fundamentals of computing :/

  • 1

    @cat which in school a lot is just like that, needed a redesign in teaching.

  • Yes, I know that video lessons are not the best way, but I’ve read a little about Oo in two books and an ebook ( C ++ & Python ). The question I ask is that I see Python abstracting a lot and therefore creating what you said yourself : 'mainstream fashion', where it is only used and not understood.

  • I’m starting to get the basis that just using class or related items ( A whatever the paradigm ) does not make the application ' Object-Oriented ' ( Or it works, structural ... ), and with that answer you helped me measure it ( :

  • I believe I must have made confusion as you yourself explained in the final part of your reply.

2

When I saw the question I remembered a chapter of the excellent book of Ramalho, Python Fluent,, when I returned to write there was already the answer of @Maniero, but to complement I decided to post my answer, based on the ideas of Ramalho.

Edited (23/07)
After a closer analysis, I realized that, to be fair, I have to agree 100% with the video, although I may have sinned, according to the author of the question, for not explaining in detail the statement that makes.

Variables are not boxes

It is quite frequent, in programming classes, the metaphor of boxes to explain the concept of variable. Luciano Ramalho in his book "Fluent Python" states that this metaphor actually hinders the understanding of reference variables in OO languages. Python variables are like Java reference variables, so it’s best to think of them as labels associated with objects. See the example below:

a = [1,2,3]
b = a
a.append(4)
b

[1, 2, 3, 4]

Thus it makes more sense to say that the variable is assigned to an object and not the other way around, i.e., the object is created before the assignment.

class Foo:
    def __init__(self):
        print ('Foo id: %d' % id(self))

bar = Foo()       
Foo id: 140015331427608


y = Foo() * 10

Foo id: 140015331465200
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-41-a4f3c60ebf6e> in <module>()
----> 1 y = Foo() * 10

TypeError: unsupported operand type(s) for *: 'Foo' and 'int'

The attempt at multiplication by a Foo instance raises an exception, but the side effect of Foo id output proves that a second instance was created before the multiplication attempt. Since variables are only labels, nothing prevents an object from having multiple labels assigned to it. When this happens, we have aliases or aliases.

joao = {'name': 'João J. Tompson', 'rg': '12345677-9' }
johny = joao
johny is joao
True

id(johny), id(joao)
(140015331669624, 140015331669624)

The is operator shows that Jonhy is a apalido (alias) for John.

Let’s change Joao through John

johny['cpf']='0988776699-00'
print (joao)
{'name': 'João J. Tompson', 'rg': '12345677-9', 'cpf': '0988776699-00'}

Now summarize that Jonah claims to be Jonah, only because he has the same credentials.

jonas = {'name': 'João J. Tompson', 'rg': '12345677-9', 'cpf': '0988776699-00' }

If we compare the values of the two objects we get True

jonas==joao
True

However, if we compare the objects (through the ID), we will see that they are not the same:

jonas is joao
False.

Of documentation

Every object has an identity, a type and a value, the identity of an object does not change after it is created, You can think of it as the address in the memory, the operator is compares the identity of two objects, the function id() returns the interior representing the identity of the object.

  • 1

    I’m glad you liked my answer, but she says the opposite of yours. I regret that some people have begun to have this understanding of variables that they are not. I regret that the current fashion is to learn abstractions and not concreteness because concrete is what really works. When you think of this form, you learn something false. Variables are boxes, roughly speaking. They’re not labels. This idea is an invention that has no foundation. In my answer there is a link that talks more about variables.

  • I understand that people confuse the object that the variable holds with its value, but that doesn’t make it true. It also has a link in my reply on types by value and by reference. I understand that some book wants to use a metaphor to simplify an explanation, but it fools the reader into thinking it’s one thing when it’s another. I will not go on three comments trying to explain the functioning of the mechanism, but is in links presented. This answer is technically correct, but leads to mistaken thinking. Do the same with a whole and none of it is worth.

  • How can the same mechanism have different behaviors? Because it does not, what explains the functioning of the integer should be the same explanation of the functioning of an object created by a class. When one conceptualizes the variable as boxes the same explanation works for the same mechanism. You just need to understand that the variable mechanism by reference has 2 boxes, one in the variables and the other in the object. The first box is an address from where the second box is.

  • It’s true, I read your answer 'un passant' and I found it very interesting, but after reading it carefully, I saw that it really contradicts mine (in some topics) and, imo, you are mistaken, at least in relation to python. Search for muttable x immutable Objects in python, and understand pq "How the same mechanism can have different behaviors".

  • This should be no different in a language, unless Python wants to be PHP and invent things. In fact I’ve never seen explanations in Python like this, because I know that Guido has a deep knowledge of how things work. Unless I’ve got something wrong, I think this is parallel creation by someone who likes to invent. Immutability has nothing to do with the fact that variables are boxes and not labels, and that’s the problem. In computing variables being were places of data storage, never a little bit. They should only change this if it had felt, and with much study.

  • Damn my... I don’t know if it would be interesting for Stopt to keep arguing here in the comments, but maybe you could understand a little better if you read at least the chapters 8 and 9 of this book.

  • But this is what I’m talking about, this book is making things up, at least based on what you said, I didn’t read it. has concepts consolidated for decades that work very well, there is no need to invent new things. Just because it’s in a book that’s just published that’s a sure thing, let alone a good one. It’s one way to explain, okay, you want to consume this you can do, but it’s not necessary. The fact that it is based on this book shows that this is something parallel and not something genuine from Python. Maybe the book doesn’t sell this idea much, but if it sells I’d say it’s just for a "novelty".

  • The book has praise from the entire python community, including from Guido, will q this account to you?

  • 1

    Also I did not mention in the answer, this "story" that variables are not boxes, in fact it is not the author of the book but a teacher of his in a course that he did at MIT.

  • It doesn’t count because I know how these things work, Guido will praise anything that gets Python out there. And the book must be good, but this point quoted is an unnecessary invention. I always keep the fundamentals, but I think everyone can follow whatever invention they want. Today the industry has too much marketing. I’m sorry that someone at MIT thinks that because they don’t have a foundation, they don’t think that the level of American universities has dropped too much. When you move away from the basics it gives it. But I have said more than I should, it does not fit here, but in my answers has these foundations all.

  • OK! Vc won. : -) But it would be interesting to consider q may be wrong. EOD.

  • 1

    Okay, decades of computation is wrong so someone found out that everyone has been wrong this whole time, but they don’t have a reliable study published and defended by the best engineers and scientists in the field, I think it’s unlikely, it’s much more likely to be invention. But nowadays opinions seem to be worth more than evidence, so there’s not much to do. That’s why I don’t buy new books, what was useful was published a long time ago, now they just copy what already existed or invent. I would even prefer the copy with a new shape, but not inventions.

  • I always consider that I may be wrong when I am offered evidence. You could consider this too, there are always sides. I read myself in every book from the '60s, '70s, '80s, '90s that I read, and read many, the most acclaimed by everyone, not by a community. But again I’m not saying that the book is bad, wrong, the point is not that.

  • Dude...you don’t see why you don’t want to, at least in relation to python, you’re this ROUNDLY mistaken, I showed this via code (first the object is created, then the assignment is made) A little humility would suit you.

  • 1

    This is a general concept, it has nothing to do with Python. It is now clear that you do not want to see what is already consolidated in a book. To tell the truth I don’t even know if the problem is the book because I’ve seen people quoting books and then I went to read, the person did not understand anything that was there. The fact that you think this has something to do with Python indicates that you may be the case. I know well the functioning of languages and Pyhton works the same as all languages in that sense, nor can it be different.

  • 1

    Actually I think you text interpretation problems because I said your answer is correct, I didn’t question it. What you just said is the same thing I said. The problem is this idea that variable is label. The computer doesn’t work like that and trying to see in other ways is wanting to not understand the correct concept. But it’s your right to do this, I never said it wasn’t. Everything it says about being open to being deceived, having humility, it’s up to you too, mainly because you’re basing it on an excerpt from a book and I’m basing it all on computing

  • 1

    As you started to get aggressive and now just want to criticize me to instead of arguing is no longer worth continuing. That sort of thing leads nowhere and it really doesn’t fit here, idea debate is a different thing. At least people can read and draw their own conclusions. And I don’t care who wants to believe in fairy tale, but who wants to know how things really work is all the information there. More can be read in other answers of mine on the subject.

  • @Sidon actually thinking of a variable as if it were a bucket or a box does not disturb at all the understanding of reference variables, nothing prevents that inside a box can contain the address of another box in which this other thing contains a literal value.

  • @Cat ok, for me the discussion is over, I believe that prolonging it will not add anything. We ended up falling in that 'pecha', "this discussion is based on opinions... and blah blah blah"

  • @Sidon I think you took it personally

  • @Sidon understands that we are here to help people simply because we want to, sometimes it is good to stay calm and be open to suggestions and criticism. And some criticism always ends up saving us ;)

  • @Gato putz.... Nothing to do, personal side? I just find it useless to stay in this discussion here. Just this. I just want to end, is there a technical chat? Invite me.

  • ' According to the author of the question, for not explaining in detail the statement it makes ' - You thought not to answer my question formulated as a piece of garbage ?! - ( Obs : >>>> ?! <<<< )

Show 18 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.