473,657 Members | 2,439 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(g et_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 2068
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__(t ype):
.... @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(ty pe):
_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__,v alue)
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_propert y_that_returns_ the_cnt_per_a_c nt_ratio() # ????
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__(t ype):
.... @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 "<interacti ve input>", line 1, in ?
File "<interacti ve input>", line 11, in ratio
ZeroDivisionErr or: 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*****@design aproduct.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(g et_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__(t ype):
... 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__.__met aclass__'>), ('_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*****@design aproduct.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(ty pe):
_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__,v alue)
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_propert y_that_returns_ the_cnt_per_a_c nt_ratio() # ????
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__(t ype):
... 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
ZeroDivisionErr or: 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.6666666666666 6663

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.4000000000000 0002

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
2431
by: Phil Powell | last post by:
Consider this: class ActionHandler { /*------------------------------------------------------------------------------------------------------------------------------------------------------------------- This class will be a singleton class structure by calling its constructor by reference only (prefixed by '&'). Is primarly used to reference its errorArray Array property as a single reference to allow for static usage
21
4063
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 A { std::vector<B*> Bs; public:
7
3889
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 TypeLib. I'm using Visual Studio .NET 2003. The original library provides simple authentication services, from Access and MS-SQL OLEDB providers. The enhancement I'm creating provides support for ODBC and will be a drop-in replacement.
9
2490
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 ride just add aditional code ontop of the current class or completely over ride it in vb? I am use to C++ this is the first inherited thing I've done in VB.NET... I'm a little unsure of diffrences, could someone explain this to me some? thanks!
3
1934
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. Would someone be so kind as to provide a small demo about classes for some
5
1953
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 class"
9
8315
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 download a file no problem. My issues come when I try to use the same class with the same commands to access an FTP server on a UNIX box. I can connect and login just fine, but after that all my commands come back "500 'PWD': command not understood."....
4
1673
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 sequentially (in the order stored) via "For Each". I know I could code this from scratch - or derived from a number of framework classes, but I'm not sure of the pros/cons of various possibilities. I'd like to use some of the new Generics - they are...
20
4030
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 tells me if a variable has changed, give me the original and current value, and whether the current value and original value is/was null or not. This one works fine but is recreating the same methods over and over for each variable type. ...
5
1891
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(); TheObject.Dictionary<string, string= new Dictionary<string, string>(); .... } The first line (TheObject instance = new TheObject();) doesn't get
0
8402
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8315
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
8829
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8734
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...
1
8508
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,...
0
7341
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, 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...
0
5633
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();...
1
2733
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
1627
bsmnconsultancy
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...

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.