473,666 Members | 1,992 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

class methods vs. functions


What are the pros and cons of defining a method of a class versus defining
a function that takes an instance of the class as an argument? In the example
below, is it better to be able to write
z.modulus() or modulus(z)? Is there a difference between Python and C++ in
this regard?

from math import sqrt
class xy:
def __init__(self,x ,y):
self.x = x
self.y = y
def modulus(self):
return sqrt(self.x**2 + self.y**2)

def modulus(z):
return sqrt(z.x**2 + z.y**2)

z = xy(3,4)
print z.modulus()
print modulus(z)

----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Jul 18 '05 #1
15 2482
On 14 Jul 2004, be*******@aol.c om wrote:
What are the pros and cons of defining a method of a class versus defining
a function that takes an instance of the class as an argument? In the example
below, is it better to be able to write
z.modulus() or modulus(z)? Is there a difference between Python and C++ in
this regard?
The answer to this, as for most questions in computer science, is "it
depends". :) The answer (which is partially my opinion) has to do with
interfaces, and what you want to accomplish:

- Case 1 -

All of your objects conform to the 'xy' interface. This interface
requeries that an object has both .x and .y member variables. You can then
define a 'modulus' function that is defined to operate on any object
implementing the 'xy' interface:
def modulus(z):
return sqrt(z.x**2 + z.y**2)
Upside:

No matter what the object is, or from where it comes, so long as it
implements the 'xy' interface, you can now take the modulus of it.

Downside:

You can't take the modulus of anything that doesn't implement 'xy'.

- Case 2 -

Some of your objects implement the 'xy' interface, others don't (e.g. they
don't make sense with it). Either way, you want to be able to find their
modulus. You can do this by making all your objects conform to the
'modulus' interface. This interface requires that an object have a
..modulus() member function:
from math import sqrt
class xy:
def __init__(self,x ,y):
self.x = x
self.y = y
def modulus(self):
return sqrt(self.x**2 + self.y**2)


Upside:

You can take the modulus of any object you create, regardless of whether
it can implement the 'xy' interface or not.

Downside:

If you aren't the designer of the object, you can't take the modulus of
it, even if it does implement the 'xy' interface.

So, the choice is up to you. You can always provide both, though:

def mymodulus(z):
try:
return z.modulus()
except AttributeError:
return modulus(z)

In case you can't tell, I'm as undecided on the issue as you ;)

Jul 18 '05 #2
On Wed, Jul 14, 2004 at 03:38:40PM -0400, Christopher T King wrote:
On 14 Jul 2004, be*******@aol.c om wrote:
What are the pros and cons of defining a method of a class versus defining
a function that takes an instance of the class as an argument?
From a technical point of view Christopher's explanation seems to be OK,

but my limited studies of object oriented programming taught me that
from outside an object you should not use its data-attributes directly.
Rather you should send the object messages, ie use methods of this object.
So z.modules() seems to be the better idea, and modules(z) the worse one.

I suppose that this means that you should treat each name foo of a
data-attribute as if it was called __foo.
egbert
--
Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991
=============== =============== =============== =============== ============
Jul 18 '05 #3
"be*******@aol. com" <be*******@127. 0.0.1:7501> writes:
What are the pros and cons of defining a method of a class versus defining
a function that takes an instance of the class as an argument? In the example
below, is it better to be able to write
z.modulus() or modulus(z)?


You're essentially comparing the message-passing paradigm to the
generic function paradigm.

One advantage of message-passing, is that it separates the messages
into namespaces, so you don't have to be as careful about chosing your
message names.

One disadvantage of message-passing, is that it separates the messages
into namespaces, so you are less careful about chosing your message
names, and end up confusing your clients. :-)

One advantage of generic functions is that multiple dispatch is much
more natural (dare I say, easier?).

One disadvantage of generic functions is that, if you are not careful,
your code ends up distributed all over the shop.

Jul 18 '05 #4
Egbert Bouwman <eg*********@hc cnet.nl> writes:
but my limited studies of object oriented programming taught me that
from outside an object you should not use its data-attributes directly.
Rather you should send the object messages,
Message-passing, while being the most common style of OO, is not the
only style of OO.

You should use the object's interface. This may or may not be
implemented via messages.
ie use methods of this object. So z.modules() seems to be the
better idea, and modules(z) the worse one.
How do you know (without looking at the implementation of
"modules") that "modules(z) " is not "using a method" ?

This is a rhetorical question, which probably needs a bit of
comment. By "method" I don't necessarily mean "Python class or
instance method". You might like to think about "add(a,b)".
I suppose that this means that you should treat each name foo of a
data-attribute as if it was called __foo.
Why treat it as private, if it isn't marked as private? If it isn't
marked as private, then it's part of the interface. If it's part of
the interface, then it is intended for use by clients. If it's
intended for use by clients, then use it.

my limited studies of object oriented programming taught me


Be careful not to let Java or C++ (or anyone strongly influenced by
them) to shape your understanding of object oriented programming. You
would be doing yourself a disservice.
Jul 18 '05 #5
On Thu, Jul 15, 2004 at 02:10:06PM +0200, Jacek Generowicz wrote:
Why treat it as private, if it isn't marked as private? If it isn't
marked as private, then it's part of the interface. If it's part of
the interface, then it is intended for use by clients. If it's
intended for use by clients, then use it.
My impression is that you can hardly call this OOO:
Object Oriented Orthodoxy. For instance, from the GOF I learned:
- the object's internal state can not be accessed directly
- operations are the only way to change an object's internal state
- requests (or messages) are the only way to get an object
to execute an operation
- a signature consists of an operation's name, parameters and return value
- the interface to an object is the set of all signatures of its operations

It is not easy to find definitions of 'interface' in python books,
but I cannot find descriptions that contradict the GOF.

And now you suggest that everything that is accessible is part
of the interface. I think I prefer the orthodoxy.

I suppose that is what you mean when you say: Be careful not to let Java or C++ (or anyone strongly influenced by
them) to shape your understanding of object oriented programming. You
would be doing yourself a disservice.

but I need more explanations, arguments, references.

You seem to encourage the following practice:
class C: pass
c = C()
c.x = 9

because the internal state of c is not private,
so it is part of the interface, so it is intended for use,
so I should use it.

I finally got rid of my goto's, and now you do this to me.
egbert

--
Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991
=============== =============== =============== =============== ============
Jul 18 '05 #6
Egbert Bouwman <eg*********@hc cnet.nl> wrote in message news:<ma******* *************** *************** @python.org>...
From a technical point of view Christopher's explanation seems to be OK,
but my limited studies of object oriented programming taught me that
from outside an object you should not use its data-attributes directly.
Rather you should send the object messages, ie use methods of this object.
So z.modules() seems to be the better idea, and modules(z) the worse one.


This argument usually stems from the idea that only calls to methods
are "sent messages". This is true in a language like C++ or Java
where a class like:

class XY {
double x, y;
double modulus();
}

allocates space for two doubles (x and y) and then puts the modulus
method in its method lookup table. The concern is that, if the owner
of class XY determines that there is a better way of representing the
data portions of the class, e.g.:

class XY {
double radians, length;
double modulus();
}

then anyone who used the XY class's data-attributes directly will then
be in trouble (since they have been removed). This is why in a
language like C++ or Java you'll usually see these fields declared as
private, and thus only the methods are considered to be part of the
class's interface.

In Python, we can avoid some of this issue because of the getattr and
setattr type functionality. Imagine I have the class:

class xy:
def __init__(self,x ,y):
self.x = x
self.y = y
def modulus(self):
return sqrt(self.x**2 + self.y**2)

And then imagine I've decided I would rather represent the class with
the radians, length formulation:

class xy:
def __init__(self, radians, length):
self.radians = radians
self.length = length
def modulus(self):
return ... # calculation in radians

Now I have to make Christopher's decision. If I believe that users of
my class never access the x and y variables, only the modulus method,
(i.e. if I envision this class with Christopher's "Case 2" interface)
then I'm done. On the other hand, if I believe that x and y are part
of the interface I've presented to users of the class, (i.e.
Christopher's "Case 1" interface), I need to continue to provide
access to these "attributes ". In Python, we can continue to make such
attributes available, even if we don't actually have an 'x' or 'y'
field in the class anymore, using the getattr/setattr functionality:

def __getattr__(sel f, name):
if name == 'x':
return ... # calculation of x from radians and length
if name == 'y':
return ... # calculation of y from radians and length
def __setattr__(sel f, name):
... # set radians or length based on x or y

So if you decide that your data attributes need to change, you haven't
destroyed compatibility with users of your class, even if your data
attributes were publicly available. Continuing to support the older
attributes isn't necessarily trivial, but at least it's /possible/
(unlike C++ or Java).

Steve
Jul 18 '05 #7
On Thu, 15 Jul 2004, Egbert Bouwman wrote:
My impression is that you can hardly call this OOO:
Object Oriented Orthodoxy. For instance, from the GOF I learned:
- the object's internal state can not be accessed directly
- operations are the only way to change an object's internal state
- requests (or messages) are the only way to get an object
to execute an operation
- a signature consists of an operation's name, parameters and return value
- the interface to an object is the set of all signatures of its operations


Replace .x with .getx() and .y with .gety() if it suits you, but often in
the case where an object is mostly used as a container (similar to a C
struct), direct access to its attributes is considered the norm:

a = 3+5j
a.real # --> 3.0
a.imag # --> 5.0

If you so choose, you can make .x and .y read-only with a little
__setattr__ magic (there's probably an easier way to do this in new-style
classes), as they are in the complex type:

a.real = 4 # --> AttributeError

Sure, it may not fit with "proper OO methodology", but it's a good way of
making visible the fact that "this object is a container, I'm retrieving
one of the variables it contains". If the interface is well-defined, it
doesn't matter how you access it, so long as you follow the interface's
design.

Jul 18 '05 #8
On Thu, Jul 15, 2004 at 09:40:53AM -0700, Steven Bethard wrote:

So if you decide that your data attributes need to change, you haven't
destroyed compatibility with users of your class, even if your data
attributes were publicly available. Continuing to support the older
attributes isn't necessarily trivial, but at least it's /possible/
(unlike C++ or Java).


Yes, I see that in real life access to the internal state of an
object is sometimes necessary. And Python allows it.

But what should i think of systems in which the users actually
have to use that licence ?

egbert
--
Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991
=============== =============== =============== =============== ============
Jul 18 '05 #9
On Thu, Jul 15, 2004 at 02:10:23PM -0400, Christopher T King wrote:
but often in
the case where an object is mostly used as a container (similar to a C
struct), direct access to its attributes is considered the norm:
Sure, it may not fit with "proper OO methodology", but it's a good way of
making visible the fact that "this object is a container, I'm retrieving
one of the variables it contains". If the interface is well-defined, it
doesn't matter how you access it, so long as you follow the interface's
design.

I am beginning to see the light. Thank you all.
egbert
--
Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991
=============== =============== =============== =============== ============
Jul 18 '05 #10

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

Similar topics

3
3045
by: Robert | last post by:
Python doesn't know the class of a method when container not direct class attribute: >>> class X: .... def f():pass .... g=f .... l= .... >>> X.g <unbound method X.f>
2
2200
by: Jerry | last post by:
My "main" class is getting a bit long...Is it possble to split a class definition into several files and then import the pieces to get the whole definition? Jerry
11
4596
by: Roger Leigh | last post by:
The C++ book I have to hand (Liberty and Horvath, Teach yourself C++ for Linux in 21 Days--I know there are better) states that "static member functions cannot access any non-static member variables". However, this doesn't seem entirely correct. It also doesn't mention whether static member functions can access protected and private member data and methods (and I couldn't spot this in the FAQ). I have a class row<Row> which derives from...
23
1454
by: patang | last post by:
When I create my own class, to use the functions of that class I have to create an object of that class and then I can access the functions of that class, for example: dim obj1 as myclass obj1 = new myclass obj1.myfunction("parameter")
10
1636
by: David Hirschfield | last post by:
Here's a strange concept that I don't really know how to implement, but I suspect can be implemented via descriptors or metaclasses somehow: I want a class that, when instantiated, only defines certain methods if a global indicates it is okay to have those methods. So I want something like: global allow allow =
22
5322
by: John Salerno | last post by:
I might be missing something obvious here, but I decided to experiment with writing a program that involves a class, so I'm somewhat new to this in Python. Anyway, what is the best way to create a function (A) within a class that another function (B) can use? Function A is not something that an instance will ever call, so I figure it's a choice between static or class methods, but I don't know which one, or if this is even the right...
17
7230
by: Fabry | last post by:
Hi All, I'm new of this group and I do not know if this is the correct group for my question. I have a DLL with its export library (.lib) wrote in Borland C++ 6. In borland everything is OK and I am able to include the lib and use the class that i have exported creating an instance with new etc... I would like to export this class in microsoft VC++ using the same .lib file. Obviously it doesn' t work.
1
1494
by: sk.rasheedfarhan | last post by:
Hi , I am using C# I am having 4 classes. like below. public class A { String m_strRuleName; String m_strRuleGuid; // Some member functions. public Object NextItem; }
1
1886
by: Bushido Hacks | last post by:
A private utility function using a function pointer sounds ideal to me. I want to simpify writing the same set of loops. While there are a few functions that can't use it, setting and modifying values sounds ideal. I would like to know if the usage of this function pointer is valid before I refactor some of the other functions that use the same data structure to complete functions. class Object
61
2949
by: Sanders Kaufman | last post by:
I'm wondering if I'm doing this right, as far as using another class object as a PHP class property. class my_baseclass { var $Database; var $ErrorMessage; var $TableName; var $RecordSet; function my_baseclass(){ $this->TableName = "";
0
8356
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8781
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8640
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6198
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5664
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();...
0
4198
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4369
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2771
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
2
2011
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.