473,545 Members | 1,977 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting rid of "self."

I think it would be cool if you could refer to instance variables
without prefixing with "self." I know noone else thinks like me so
Python will never be changed, but maybe you can already do it with
Python today?

..import sys
..
..def magic():
.. s = ""
.. for var in sys._getframe(1 ).f_locals["self"].__dict__:
.. s += var + " = self." + var + "\n"
.. return s
..
..class A:
.. def __init__(self):
.. self.hi = "yo"
..
.. def meth(self):
.. exec(magic())
.. print hi
..
..a = A()
..a.meth()

It works! exec(magic()) does the needed hi = self.hi. Not so
impressive in this case but much cooler when there is more instance
variables around. But the solution is very ugly because you have to
write exec(magic()) in every method. So I'm asking here if someone
knows a better way, maybe using decorators or metaclasses or other
black magic?
--
mvh Björn
Jul 18 '05 #1
5 2820
BJörn Lindqvist a écrit :
I think it would be cool if you could refer to instance variables
without prefixing with "self." I know noone else thinks like me so
Python will never be changed, but maybe you can already do it with
Python today?
(snip code)
It works! exec(magic()) does the needed hi = self.hi. Not so
impressive in this case but much cooler when there is more instance
variables around. But the solution is very ugly because you have to
write exec(magic()) in every method. So I'm asking here if someone
knows a better way, maybe using decorators or metaclasses or other
black magic?


The better way is definitively to forget about black magic and
understand why mandatory 'self' is Good Thing (tm).

(Tip : even when [this|self|@|wha tsoever] is not mandatory, using it
makes for much more readable code.)

Bruno

Jul 18 '05 #2

"BJörn Lindqvist" <bj*****@gmail. com> wrote in message
news:ma******** *************** *************** @python.org...
I think it would be cool if you could refer to instance variables
without prefixing with "self." I know noone else thinks like me so
Python will never be changed, but maybe you can already do it with
Python today?

....

It works! exec(magic()) does the needed hi = self.hi. Not so
impressive in this case but much cooler when there is more instance
variables around. But the solution is very ugly because you have to
write exec(magic()) in every method. So I'm asking here if someone
knows a better way, maybe using decorators or metaclasses or other
black magic?

[response]

Having to specify the instance explicitly is something that
Python needs because it isn't a statically typed language.
In a statically typed language, all variables are pre-declared,
so the compiler knows where they all are.

Python's compiler knows about local variables. It
doesn't know where any other variables are, so it
has to search. Including the instance as one of the
method parameters means that the search splits
right at the front: either it starts looking up the
instance, or it goes up the definition chain (usually
empty) to the module namespace and then the
builtins.

Eliminating "self" would mean it would have to
either search the instance before the module and
builtins, or search the module and builtins before
the instance. This is both a performance issue
and a maintenance issue because of the increased
possibility of one shadowing the other.

This is distinct from the issue of how to spell
"self". As another responder has already said,
you can spell it any way you want; it's simply
whatever you choose to call the first paramteter
to the method.

Going the other way, the word "self" could become
a keyword, removing the necessity of specifying it
among the method parameters. While I like the idea,
there's enough dislike of the notion that it's not going
to happen.

John Roth
--
mvh Björn

Jul 18 '05 #3
On Fri, 07 Jan 2005 14:39:09 +0100, BJörn Lindqvist wrote:
It works! exec(magic()) does the needed hi = self.hi.


No it doesn't. Try "hi = 'newValue'" and see what happens.

So the next step is to write an "unmagic" function. So now how do you add
instance variables?

There is no way to avoid "self" *and* not pre-declare variables in some
fashion as belonging to the instance (as declarations, as sigils, what
have you). Given that Python is not, will not, and should not do the
latter, I submit that "self" is, at least for you, the lesser of two
evils. (I don't consider it evil at all, so it isn't such for me; were I
programming in C++ routinely now I'd prefix "this" and dispense with that
ugly "m_" garbage. (One of the things I ***hate*** about C++ culture is
its acceptance of hideously ugly variable names, but now I'm two
parentheticals deep so I probably ought to stop.))
Jul 18 '05 #4
Jeremy Bowers <je**@jerf.or g> wrote:
were I programming in C++ routinely now I'd prefix "this" and
dispense with that ugly "m_" garbage. (One of the things I ***hate***
about C++ culture is its acceptance of hideously ugly variable names,
but now I'm two parentheticals deep so I probably ought to stop.))


I'm currently working in a C++ system where they have a wrapper class
that provides some transaction locking functionality for member access.
The colloquial name for the wrapped "this" pointer is self, i.e. they do
"self = wrapper (this)" at the beginning of functions that need it. You
can then do "member" to get the bare access or "self.membe r" to get the
locking functionality.

It's actually kind of neat, but boy does it play headgames with me when
I switch back and forth between that and Python.
Jul 18 '05 #5
Roy Smith wrote:
It's actually kind of neat, but boy does it play headgames with me when
I switch back and forth between that and Python.


Switching back and forth betwen C++ and Python plays headgames *anyway* }:>

Cheers,
Nick.
Hardware control with Python is nice. . .

--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2419
by: Todd Gardner | last post by:
Pardon my extremely ignorant newbie questions. Where can I go to find more information about the "self" argument? Is there something special about the word "self" or did Mr. Guido van Rossum just decide to us the word arbitrarily? More precisely it seems that most all classes have "self" as the first parameter. This may be directly...
1
1623
by: Olaf Meding | last post by:
What does the below PyChecker warning mean? More importantly, is there a way to suppress it? PyChecker warning: ..\src\phaseid\integration.py:21: self is argument in staticmethod My best guess is that the warning is related to PyChecker not supporting C++ extensions.
26
2151
by: Fernando M. | last post by:
Hi, i was just wondering about the need to put "self" as the first parameter in every method a class has because, if it's always needed, why the obligation to write it? couldn't it be implicit? Or is it a special reason for this being this way? Thanks.
20
2836
by: Wayne Sutton | last post by:
OK, I'm a newbie... I'm trying to learn Python & have had fun with it so far. But I'm having trouble following the many code examples with the object "self." Can someone explain this usage in plain english? Thanks, Wayne
9
2735
by: shannonl | last post by:
Hi all, For some reason this bind is calling the donothing function, like it should, but is then allowing the text to be inserted into the Text widget. Here is the code: self.framebody.tag_config("name", underline=1) self.framebody.tag_bind("name", "<Any-KeyPress>", self.donothing)
13
11995
by: Kurda Yon | last post by:
Hi, I found one example which defines the addition of two vectors as a method of a class. It looks like that: class Vector: def __add__(self, other): data = for j in range(len(self.data)): data.append(self.data + other.data)
8
2685
by: ssecorp | last post by:
I first learned about OO from Java. I much prefer to program in Python though. However I am consufed about 2 things. 1. Why do I have to pass self into every method in a class? Since I am always doing why cant this be automated or abstracted away? Are the instances where I won't pass self? I imagine there is some tradeoff involved...
0
7478
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7410
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7923
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7773
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5343
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4960
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3466
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1025
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.