This one has always bugged me. Is it better to just slap a "self" in
front of any variable that will be used by more than one class method
or should I pass around variable between the methods?
Flamewar....... .NOW!
jk, I really do want other opinions.
Thanks,
Derek 14 9841
On 1 Mar 2006 11:32:02 -0800, Derek Basch wrote: This one has always bugged me. Is it better to just slap a "self" in front of any variable that will be used by more than one class method or should I pass around variable between the methods?
I think there is no clear "general" answer. A criterion could be that
instance variables should be those who define the state of the object, that
define its "meaning".
About the others to me it's a matter of taste.
--
USB Priests for only 10$
On Wed, 1 Mar 2006, Derek Basch wrote: This one has always bugged me. Is it better to just slap a "self" in front of any variable that will be used by more than one class method or should I pass around variable between the methods?
As a general rule, I only turn a parameter into an instance variable when
it would otherwise be a parameter of all (or nearly all) methods. Though
this is perhaps an overly mechanical perspective, I like to think of
instance variables as implicit parameters to every method. It helps me
keep scope under control and encourages better cohesion.
--
.:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:.
"one man's constant is another man's variable" - alan perlis
On Wed, 01 Mar 2006 11:32:02 -0800, Derek Basch wrote: This one has always bugged me. Is it better to just slap a "self" in front of any variable that will be used by more than one class method or should I pass around variable between the methods?
That depends on whether the variable is conceptually an attribute of the
instance or a parameter.
Attributes of the instance should be made instance attributes by (as you
put it) slapping a "self" in front of it. Parameters of the methods should
be passed around as arguments to the methods.
--
Steven.
On 1 Mar 2006 11:32:02 -0800
"Derek Basch" <db****@yahoo.c om> wrote: This one has always bugged me. Is it better to just slap a "self" in front of any variable that will be used by more than one class method or should I pass around variable between the methods?
My first reaction was that they should always be object
properties -- that passing values between methods of the
same object is always a bad idea. But on further reflection,
I'm not sure that's really the rule I use, so here's a
better attempt:
Are the values in question properties of the object?
If I make two calls to the object from unrelated processes,
should those values be the same, or different for each
caller?
If they need to be different for each caller, then you might
need to pass them around. If however, they are the same
because it's the same object, then they ought to be
expressed as properties of the object.
It's funny, I've never actually had any doubts about
which to use in practice, it always seems obvious, so
it's hard to recall what my actual thought process is
on the subject.
--
Terry Hancock (ha*****@Anansi Spaceworks.com)
Anansi Spaceworks http://www.AnansiSpaceworks.com
Derek Basch wrote: This one has always bugged me. Is it better to just slap a "self" in front of any variable that will be used by more than one class method or should I pass around variable between the methods?
Flamewar....... .NOW!
jk, I really do want other opinions.
Thanks, Derek
I tend to think in terms of states. If a quantity/attribute is important
for the state of an object, then it should be an instance variable. If
it can be calculated from the state, then it can be made a read-only
property, etc. If it is irrelevant to the state of an object, it
probably should belong to another object or should be a global.
Here is an example from chemistry:
densities = {'H2O' : 1.0, 'Hg' : 13.6}
class CupOfLiquid(obj ect):
def __init__(self, liquid, volume):
self.liquid = liquid
self.volume = volume
def spill(self, spill_vol):
newvol = self.volume - spill_vol
if newvol < 0:
raise SpillError, "Can't spill that much!"
self.volume = newvol
def get_mass(self):
return densities[self.liquid] * self.volume
mass = property(get_ma ss)
Notice that it would be quite awkward to remember the volume state of a
CupOfLiquid instance between method calls. One would need a global to do
this, which defeats the purpose of using classes (i.e. object
orientation). Notice also that the value of densities is independent of
the state of any CupOfLiquid instance, so it is a global.
As an exercise, try threading this object for evaporation. Hint, you
might need a "lid_closed " attribute.
James
Derek Basch wrote: This one has always bugged me. Is it better to just slap a "self" in front of any variable that will be used by more than one class method or should I pass around variable between the methods?
Try to distinguish the state of the object from the parameters to methods.
An object should always have a consistent state. Say you call a method, and
that method calls a bunch of other methods. At almost any point during
those method calls execution can leak out to other bits of code (e.g. you
might think you are adding two values, but perhaps they have a user defined
addition operator) and that other code might just call methods on the same
object. This might not happen much in practice, but I think that if you
imagine all method calls as potentially happening in parallel it avoids a
lot of problems.
So, for example, if you had a method which returned a formatted
representation of something, and which took a precision as a parameter, you
shouldn't be saving the precision in the object: it isn't part of the
state, and if you save it as such one day you might find it changes under
your feet mid call.
A lot of objects benefit from being treated as immutable: i.e. initialise
them on creation, but never modify the attributes after creation. This has
the great benefit that you never need to worry about whether or not to copy
an object: you always just keep using the same object until an attribute
needs to change and then you just create a new one. Obviously this only
works for lightweight objects, but that should be most of them.
Passing one or two parameters around a host of methods is fine: if you are
passing more then it probably indicates you need to invent another object
to encapsulate the state associated with the method call. It is also likely
that it means you then want to move some of the code logic into the new
object. In other words, instead of:
obj.meth1(a, b, c, d) calls obj.meth2(a, b, c, d) calls obj.meth3, ...
(and perhaps meth2 only needs a, b and c so it can pass them on),
you want some helper object constructed with a, b, c & d and parts of the
original methods then get factored into methods on the help objects.
Derek Basch wrote: This one has always bugged me. Is it better to just slap a "self" in front of any variable that will be used by more than one class method
s/class method/method/
In Python, a "class method" is a method working on the class itself (not
on a given instance).
or should I pass around variable between the methods?
One of the first rules I learned (from experience...) was to restrict as
much as possible the scope of a variable. It usually makes code more
readable, more robust, and more modular. In fact, I sometime even pass
attributes of an object as args to a method of the same object, and/or
assign values returned from a method of an object to attributes of the
same object. This is more explicit than relying on side-effects.
So (as pointed by almost everyone in this thread...) the best criteria
here is : is this variable part of the state of an object, or is it just
a value used for a given computation ?
Note that if you find yourself passing the same huge set of variables
from method to method for a given computation, this may calls for a
refactoring... Python objects can be callable (ie function-like), so a
complex computation with lot of shared state (independant from the rest
of the object) may be best implemented as a separate temporary callable
object - which can take the calling object as a parameter if it needs to
access other attributes from it.
My 2 cents...
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Wow! Thanks everyone. Such coherent and philisophical answers. I will
read them all over on a lazy sunday as this type ethereal stuff hurts
my head after about 30 seconds. All the gurus on the python list are so
friggin' smart. This should improve my coding after I digest it all.
Thanks Again!
Derek Basch
So, if I am understanding what everyone is saying here. I should do my
best to distinguish between values that are part of the "state" of an
object and values that are more disposable and can change for each
computation of a value. So if I create an instance of a "wallet" class
and the color of the wallet is "red". The "red" value would be ideal as
a class variable as it is tied to the state of that wallet instance.
However, if the wallet class contains a function to compute the tax on
a purchased item, the purchase price would be a good example of a
passed parameter value. Am I on the right track?
Thanks,
Derek Basch This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Dan |
last post by:
I have seen differing ways to pass values to a class:
$db=new mysqlclass('localhost','user','passwd','database');
.....
OR
$db=new mysqlclass()
$db->host='localhost';
$db->user='user';
$db->passwd='passwd';
|
by: surrealtrauma |
last post by:
the requirement is :
Create a class called Rational (rational.h) for performing arithmetic with
fractions. Write a program to test your class.
Use Integer variables to represent the private data of the class – the
numerator and the denominator. Provide a constructor that enables an
object of this class to be initialized when it is declared. The
constructor should contain default values in case no initializers are
provided and should...
|
by: Bryan Olson |
last post by:
The current Python standard library provides two cryptographic
hash functions: MD5 and SHA-1 . The authors of MD5 originally
stated:
It is conjectured that it is computationally infeasible to
produce two messages having the same message digest.
That conjecture is false, as demonstrated by Wang, Feng, Lai and
Yu in 2004 . Just recently, Wang, Yu, and Lin showed a short-
cut solution for finding collisions in SHA-1 . Their result
|
by: news |
last post by:
Well, I wrote my first PHP class today. Yeah!
But to get it to work, in each function within the class I have to
repeat the database connection lines, and that just seems redundant;
there has to be a better way that I'm just not bright enough to think
of.
Any suggestions?
(It's the first 3 lines of each of the two functions below. When I have
it fully written, there will be about 10 similar functions, each
repeating those three lines.)
|
by: Sai Kit Tong |
last post by:
I posted for help on legacy code interface 2 days ago. Probably I didn't
make it clear in my original mail. I got a couple of answers but none of
them address my issues directly (See attached response). My first reply
directed me to source code migration but I didn't have the source code. The
second reply mentioned about .NET interoperability (PInvoke I think) but I
MENTIONED THAT I COULDN'T FIND ANY DOCUMENTATION FROM MSDN LIBRARY BASED ON...
| |
by: Chris |
last post by:
Hi,
I don't get the difference between a struct and a class !
ok, I know that a struct is a value type, the other a reference type, I
understand the technical differences between both, but conceptually speaking
: when do I define something as 'struct' and when as 'class' ?
for example : if I want to represent a 'Time' thing, containing :
- data members : hours, mins, secs
|
by: AlexVN |
last post by:
Hi,
I would like to know if someone investigated the method of creating
classes dynamically depending on the name. I do not like a lot of ifs
and I suppose that something like call_user_func_array('ClassName',
array($param1, $param2, $param3, ..., $paramN)) should exist over the
PHP language. Any suggestions?
Thanks,
Alexander
|
by: Coleen |
last post by:
Hi All :-)
I am desperately looking for some help/information on how to direct page
flow. Forget what I have done - here's what I need to do:
I have a large ASPX.Net - VB.Net web application (around 35-40 pages) that
once the user logs in, I need to direct them to the correct page, depending
on what they select from the directory. In other words...when they login,
if they are a new user, a new account screen comes up and from there a...
|
by: Rafe |
last post by:
Hi,
I'm working within an application (making a lot of wrappers), but the
application is not case sensitive. For example, Typing obj.name,
obj.Name, or even object.naMe is all fine (as far as the app is
concerned). The problem is, If someone makes a typo, they may get an
unexpected error due accidentally calling the original attribute
instead of the wrapped version. Does anyone have a simple solution for
this?
|
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 usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
| |
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
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 into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |