[C++-SIG] setattr and CXX-4.2

Phil Austin phil at geog.ubc.ca
Wed May 17 21:05:45 CEST 2000


Barry Scott writes:
 > 
 > setattr is not allowed to create functions or mess up __methods__ so you simply
 > handle your non-function attributes and throw Py::NameError for all you know
 > nothing about.
 > 

Thanks, that lifted the fog a little.  Here's a couple of patches to
r.h and r.cxx that set an attribute, for the mailing list archive and, 
in case you want to expand the demo to exercise this:

*** r.h	2000/05/17 18:00:05	1.1
--- r.h	2000/05/17 18:20:51
***************
*** 8,13 ****
--- 8,15 ----
  
  // Making an extension object
  class r: public Py::PythonExtension<r> {
+ private:
+     Py::Object setme;  
  public:
      long	start;
      long	stop;
***************
*** 54,59 ****
--- 56,62 ----
      // override functions from PythonExtension
      virtual Py::Object repr();
      virtual Py::Object getattr( const char *name );
+     virtual int setattr( const char *name, const Py::Object & );
  
      virtual int sequence_length();
      virtual Py::Object sequence_item( int i );



*** r.cxx	2000/05/04 18:46:23	1.1
--- r.cxx	2000/05/17 18:36:18
***************
*** 43,51 ****
--- 43,66 ----
      if(std::string(name) == "start")
  		return Py::Int(start);
  
+     if(std::string(name) == "setme")
+ 		return setme;
+ 
      return getattr_methods( name );
  }
  
+ int r::setattr( const char *name,const Py::Object& rhs )
+ {
+ 
+    if(std::string(name) == "setme"){
+ 		setme=rhs;
+ 		return(0);
+    }
+ 
+    throw Py::AttributeError ("setAttr failed.");;
+ }
+ 
+ 
  // "regular" methods...
  Py::Object r::amethod( const Py::Tuple &t ) 
  {
***************
*** 81,86 ****
--- 96,102 ----
  	behaviors().doc("r objects: start, stop, step");
  	behaviors().supportRepr();
  	behaviors().supportGetattr();
+ 	behaviors().supportSetattr();
  	behaviors().supportSequenceType();
  
  	add_varargs_method("amethod", &r::amethod,


Python 1.5.2 (#2, Aug 26 1999, 22:59:52) [C] on sunos5
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import example
>>> my_r=example.r(1,12,4)
>>> my_r.setme
>>> my_r.setme=[1,2,3]
>>> my_r.setme
[1, 2, 3]




More information about the Cplusplus-sig mailing list