473,425 Members | 1,673 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,425 software developers and data experts.

Class property (was: Class methods)

Hughes, Chad O wrote:
Is there any way to create a class method? I can create a class
variable like this:

Hmm, seeing this post, I have decided to implement a 'classproperty'
descriptor.
But I could not. This is what I imagined:

class A(object):
_x = 0
@classmethod
def get_x(cls):
print "Getting x..."
return cls._x
@classmethod
def set_x(cls,value):
print "Setting x..."
cls._x = value
x = classproperty(get_x,set_x)

Usage example:
print A.x Getting x
0A.x = 8 Setting xprint A.x

Getting x
8

I was trying for a while, but I could not implement a 'classproperty'
function. Is it possible at all?
Thanks,

Les


Oct 6 '05 #1
5 2049
Laszlo Zsolt Nagy wrote:
I was trying for a while, but I could not implement a 'classproperty'
function. Is it possible at all?


You could define a "normal" property in the metaclass:
> class A: .... class __metaclass__(type):
.... @property
.... def clsprp(cls): return 42
.... A.clsprp

42

Peter

Oct 6 '05 #2
Peter Otten wrote:
Laszlo Zsolt Nagy wrote:
I was trying for a while, but I could not implement a 'classproperty'
function. Is it possible at all?


You could define a "normal" property in the metaclass:

The only way I could do this is:

class MyXMetaClass(type):
_x = 0
def get_x(cls):
print "Getting x"
return cls._x
def set_x(cls,value):
cls._x = value
print "Set %s.x to %s" % (cls.__name__,value)
x = property(get_x,set_x)

class A(object):
__metaclass__ = MyXMetaClass

print A.x
A.x = 8
Results in:

Getting x
0
Set A.x to 8

But of course this is bad because the class attribute is not stored in
the class. I feel it should be.
Suppose we want to create a class property, and a class attribute; and
we would like the property get/set methods to use the values of the
class attributes.
A real example would be a class that keeps track of its direct and
subclassed instances:

class A(object):
cnt = 0
a_cnt = 0
def __init__(self):
A.cnt += 1
if self.__class__ is A:
A.a_cnt += 1

class B(A):
pass

print A.cnt,A.a_cnt # 0,0
b = B()
print A.cnt,A.a_cnt # 1,0
a = A()
print A.cnt,A.a_cnt # 2,1

But then, I may want to create read-only class property that returns the
cnt/a_cnt ratio.
This now cannot be implemented with a metaclass, because the metaclass
cannot operate on the class attributes:

class A(object):
cnt = 0
a_cnt = 0
ratio = a_class_property_that_returns_the_cnt_per_a_cnt_ra tio() # ????
def __init__(self):
A.cnt += 1
if self.__class__ is A:
A.a_cnt += 1

Any ideas?

Les

Oct 6 '05 #3
Laszlo Zsolt Nagy wrote:
class A(object):
cnt = 0
a_cnt = 0
def __init__(self):
A.cnt += 1
if self.__class__ is A:
A.a_cnt += 1
class B(A):
pass
print A.cnt,A.a_cnt # 0,0
b = B()
print A.cnt,A.a_cnt # 1,0
a = A()
print A.cnt,A.a_cnt # 2,1

But then, I may want to create read-only class property that returns the
cnt/a_cnt ratio.
This now cannot be implemented with a metaclass, because the metaclass
cannot operate on the class attributes:


Huh? Every function in the metaclass takes the class object as the
first parameter. So they can all operate on the class attributes:

py> class A(object):
.... cnt = 0
.... a_cnt = 0
.... def __init__(self):
.... A.cnt += 1
.... if self.__class__ is A:
.... A.a_cnt += 1
.... class __metaclass__(type):
.... @property
.... def ratio(cls):
.... return cls.a_cnt/float(cls.cnt)
....
py> class B(A):
.... pass
....
py> A.cnt, A.a_cnt
(0, 0)
py> A.ratio
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 11, in ratio
ZeroDivisionError: float division
py> b = B()
py> A.cnt, A.a_cnt, A.ratio
(1, 0, 0.0)
py> a = A()
py> A.cnt, A.a_cnt, A.ratio
(2, 1, 0.5)

STeVe
Oct 11 '05 #4
On Thu, 06 Oct 2005 11:05:10 +0200, Laszlo Zsolt Nagy <ga*****@designaproduct.biz> wrote:
Hughes, Chad O wrote:
Is there any way to create a class method? I can create a class
variable like this:

Hmm, seeing this post, I have decided to implement a 'classproperty'
descriptor.
But I could not. This is what I imagined:

class A(object):
_x = 0
@classmethod
def get_x(cls):
print "Getting x..."
return cls._x
@classmethod
def set_x(cls,value):
print "Setting x..."
cls._x = value
x = classproperty(get_x,set_x)

Usage example:
print A.xGetting x
0A.x = 8Setting xprint A.xGetting x
8

I was trying for a while, but I could not implement a 'classproperty'
function. Is it possible at all?
Thanks,

Les

Using Peter's advice (not tested beyond what you see):
class A(object): ... _x = 0
... class __metaclass__(type):
... def get_x(cls):
... print "Getting x..."
... return cls._x
... def set_x(cls,value):
... print "Setting x..."
... cls._x = value
... x = property(get_x, set_x)
... A.x Getting x...
0 A.x = 8 Setting x... A.x Getting x...
8 vars(A).items() [('__module__', '__main__'), ('__metaclass__', <class '__main__.__metaclass__'>), ('_x', 8), ('_
_dict__', <attribute '__dict__' of 'A' objects>), ('__weakref__', <attribute '__weakref__' of 'A
' objects>), ('__doc__', None)] A._x 8 vars(A).keys()

['__module__', '__metaclass__', '_x', '__dict__', '__weakref__', '__doc__']

Regards,
Bengt Richter
Oct 15 '05 #5
On Thu, 06 Oct 2005 16:09:22 +0200, Laszlo Zsolt Nagy <ga*****@designaproduct.biz> wrote:
Peter Otten wrote:
Laszlo Zsolt Nagy wrote:
I was trying for a while, but I could not implement a 'classproperty'
function. Is it possible at all?
You could define a "normal" property in the metaclass:

The only way I could do this is:

class MyXMetaClass(type):
_x = 0
def get_x(cls):
print "Getting x"
return cls._x
def set_x(cls,value):
cls._x = value
print "Set %s.x to %s" % (cls.__name__,value)
x = property(get_x,set_x)

class A(object):
__metaclass__ = MyXMetaClass

print A.x
A.x = 8
Results in:

Getting x
0
Set A.x to 8

But of course this is bad because the class attribute is not stored in
the class. I feel it should be.
Suppose we want to create a class property, and a class attribute; and
we would like the property get/set methods to use the values of the
class attributes.
A real example would be a class that keeps track of its direct and
subclassed instances:

class A(object):
cnt = 0
a_cnt = 0
def __init__(self):
A.cnt += 1
if self.__class__ is A:
A.a_cnt += 1

class B(A):
pass

print A.cnt,A.a_cnt # 0,0
b = B()
print A.cnt,A.a_cnt # 1,0
a = A()
print A.cnt,A.a_cnt # 2,1

But then, I may want to create read-only class property that returns the
cnt/a_cnt ratio.
This now cannot be implemented with a metaclass, because the metaclass
cannot operate on the class attributes:

But it can install a property that can.
class A(object):
cnt = 0
a_cnt = 0
ratio = a_class_property_that_returns_the_cnt_per_a_cnt_ra tio() # ????
def __init__(self):
A.cnt += 1
if self.__class__ is A:
A.a_cnt += 1

Any ideas?

class A(object): ... cnt = 0
... a_cnt = 0
... def __init__(self):
... A.cnt += 1
... if self.__class__ is A:
... A.a_cnt += 1
... class __metaclass__(type):
... def ratio(cls):
... print "Getting ratio..."
... return float(cls.a_cnt)/cls.cnt #
... ratio = property(ratio)
...
I inverted your ratio to lessen the probability if zero division...
class B(A): pass ... A.ratio Getting ratio...
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 11, in ratio
ZeroDivisionError: float division

Oops ;-)
A.cnt, A.a_cnt (0, 0) b=B()
A.cnt, A.a_cnt (1, 0) A.ratio Getting ratio...
0.0 a=A()
A.ratio Getting ratio...
0.5
a=A()
A.ratio Getting ratio...
0.66666666666666663

The old instance is no longer bound, so should it still be counted as it is?
You might want to check how to use weak references if not...
b2=B()
B.ratio Getting ratio...
0.5 b3=B()
B.ratio

Getting ratio...
0.40000000000000002

Regards,
Bengt Richter
Oct 15 '05 #6

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

Similar topics

1
by: Phil Powell | last post by:
Consider this: class ActionHandler { ...
21
by: Jon Slaughter | last post by:
I have a class that is basicaly duplicated throughout several files with only members names changing according to the class name yet with virtually the exact same coding going on. e.g. class...
7
by: TJ | last post by:
In C# how do you achieve pass-by-reference property declarations in the Type Library? I am writing a COM Class Library that must mimick an existing library for which the only information is the...
9
by: Brian Henry | last post by:
If i inherite a queue class into my class, and do an override of the enqueue member, how would i then go about actually doing an enqueue of an item? I am a little confused on this one... does over...
3
by: Trammel | last post by:
Hi, I recently upgraded to VB.net from VB6.. and woah... I feel lost :¬O One of my reasons for upgrading is I was told that VB.net can do class inheritance and subclassing easier. ...
5
by: Rob | last post by:
In many articles related to VB.net the word "class" is used... How many meanings are there to this word ? "possible to derived a class from another" "forms are full-fledged classes" "base...
9
by: craig.overton | last post by:
All, I am currently developing an FTP class in VB.NET. It's kid tested, mother approved when trying to access an FTP Server on a Windows box meaning I can connect, run commands, upload and...
4
by: Mark | last post by:
I want to create a collection class that will be strongly typed (store a specific object type), be keyed with a case insensitive string, and be able to access objects stored by index, or...
20
by: tshad | last post by:
Using VS 2003, I am trying to take a class that I created to create new variable types to handle nulls and track changes to standard variable types. This is for use with database variables. This...
5
by: Andy B | last post by:
I am trying to figure out how to make an object instance available for all methods of a class. I tried to do something like this: public class test { TheObject Instance = new TheObject();...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
1
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...
0
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...
0
agi2029
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,...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.