473,796 Members | 2,635 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

classes are objects... so how can we custom print them: we need a classmethod syntax

Hello,

In Python, classes are objects. But there is no way to custom print a class
object. This would require some syntax such as the one commented out below:
With the current "foo = classmethod(foo )" mechanism custom printing for
class objects is not possible.

#!/usr/bin/python

class Foo:
def __str__(self):
return "foo"
#def classmethod __str__(cls):
# return "pythons bite"

foo = Foo()
s = "hello %s!" % foo # custom text here
print s

print Foo # no custom text here possible it seems, unless we call
# a staticmethod such as Foo.printMe()

Regards,

Neil
Jul 18 '05 #1
3 1975
Neil Zanella wrote:
Hello,

In Python, classes are objects. But there is no way to custom print a class
object. This would require some syntax such as the one commented out below:
With the current "foo = classmethod(foo )" mechanism custom printing for
class objects is not possible.

#!/usr/bin/python

class Foo:
def __str__(self):
return "foo"
#def classmethod __str__(cls):
# return "pythons bite"

foo = Foo()
s = "hello %s!" % foo # custom text here
print s

print Foo # no custom text here possible it seems, unless we call
# a staticmethod such as Foo.printMe()


You need Metaclasses for that. Consider:
class PrintTest(objec t): .... class __metaclass__(t ype):
.... def __str__(self):
.... return "I'm a PrintTest"
.... print PrintTest I'm a PrintTest


Reinhold

--
Wenn eine Linuxdistributi on so wenig brauchbare Software wie Windows
mitbrächte, wäre das bedauerlich. Was bei Windows der Umfang eines
"kompletten Betriebssystems " ist, nennt man bei Linux eine Rescuedisk.
-- David Kastrup in de.comp.os.unix .linux.misc
Jul 18 '05 #2
From my metaclasses presentation:

"""Simple example of changing class repr"""
class Meta( type ):
def __repr__( cls ):
return '<OhLookAMetaCl ass>'
class X:
__metaclass__ = Meta

# this uses the meta-property for lookup
assert repr(X) == '<OhLookAMetaCl ass>'

Code and presentation available at:
http://www.vrplumber.com/programming/

HTH,
Mike

Neil Zanella wrote:
Hello,

In Python, classes are objects. But there is no way to custom print a class
object. This would require some syntax such as the one commented out below:
With the current "foo = classmethod(foo )" mechanism custom printing for
class objects is not possible.

....

_______________ _______________ _______________ ___
Mike C. Fletcher
Designer, VR Plumber, Coder
http://www.vrplumber.com
http://blog.vrplumber.com

Jul 18 '05 #3
Neil Zanella wrote:
Hello,

In Python, classes are objects. But there is no way to custom print a
class object. This would require some syntax such as the one commented out
below: With the current "foo = classmethod(foo )" mechanism custom printing
for class objects is not possible.

#!/usr/bin/python

class Foo:
def __str__(self):
return "foo"
#def classmethod __str__(cls):
# return "pythons bite"

foo = Foo()
s = "hello %s!" % foo # custom text here
print s

print Foo # no custom text here possible it seems, unless we call
# a staticmethod such as Foo.printMe()

Regards,

Neil


Classes are objects. You have to define the __str__() method in the object's
class - for a class that would be the metaclass. Now here:
class FooType(type): .... def __str__(self):
.... return "custom text for class %s" % self.__name__
.... class Foo: .... __metaclass__ = FooType
.... def __str__(self):
.... return "custom text for %s instance" %
self.__class__. __name__
.... print Foo() custom text for Foo instance print Foo custom text for class Foo


Peter

Jul 18 '05 #4

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

Similar topics

2
1820
by: Jay Moore | last post by:
I hope this isn't asking too much but here goes: Can someone explain to me in a simple way on how to use classes, and -- more importantly -- WHY to use them? I'm not a complete rookie to PHP, but I've never really understood classes. Please help. TIA,
7
2401
by: Bo Peng | last post by:
Dear Python group: I am planning on an application that involves several complicated C++ classes. Basically, there will be one or two big data objects and some "action" objects that can act on the data. I would like to use a script language to control the interaction between these c++ objects. I become interested in Python since it can load C++ objects and can even extend C++ classes. However, I am not quite sure to what extent can...
1
2674
by: Jordan | last post by:
I have written a small C# application that will print out labels from a little label printer we have. However the size (how long the label is) is determined by a database call. I need to specify a custom paper size every time the print button is clicked. Is there a way to set a custom print size on the fly? I read somewhere else on the newsgroup that you can't do
3
1202
by: Tambi | last post by:
How can I get an object address as IntPtr ? Somehow even in unsafe it's not working with objetcs... I'am trying to compare two objects that are not the same but could be from some point. Example : Let say we have two classes one derived from another
2
1106
by: wrytat | last post by:
I have a web application. There's 1 part whereby I'll show a list of items (order). I did this by using classes and objects. I defined my own classes (called orderitem and ordermanager), and my aspx file just call the ordermanager to connect to the SQL 2000 server, perform stored procedure, get the required data and convert them into orderitem and push them into an arraylist. Finally it will return this arraylist and my aspx file just read...
0
1404
by: shapper | last post by:
Hello, I need to create a custom SiteMapProvider. I searched in Google for examples but I am still completly lost. The custom SiteMapProvider I need to create is exactly the same as the Asp.Net SiteMapProvider: The only difference is: attribute Visible = "True".
2
1344
by: djsdaddy | last post by:
Good Day to All, I am organizing some Affirmative Action data and I need to be able to sum a number of field totals and then print them in a report. I have 5 tables that store the data that I need for this report: 1) tblMasterEmployee - relates the next 3 tables by EmployeeID 2) tblEmployeeDates - need Date of Hire and Termination Date (if applicable) 3) tblEEO-Promotions - Keeps track of employee promotions 4) tblEEO-EmployeeData -...
9
2827
by: rushdi | last post by:
hi, i am trying to convert nos to a special format then print them into a text file. is it possible ? can anyone help me please ?
7
1429
by: bukzor | last post by:
I was trying to change the behaviour of print (tee all output to a temp file) by inheriting from file and overwriting sys.stdout, but it looks like print uses C-level stuff to do its writes which bypasses the python object/inhertiance system. It looks like I need to use composition instead of inheritance, but thought this was strange enough to note. $python -V Python 2.5
0
9685
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
10465
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...
1
10200
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,...
1
7558
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
6800
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
5453
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
5582
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4127
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
3
2931
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.