sending a class as an argument

Gabriel Genellina gagsl-py at yahoo.com.ar
Mon Jan 29 23:53:47 EST 2007


En Mon, 29 Jan 2007 01:24:23 -0300, manstey <manstey at csu.edu.au> escribió:

>
> Our class has its attributes set as classes, as in
>
> MyClass.Phone.Value='34562346'
> MyClass.Phone.Private=True
>
> Inside the MyClass definition we have a function like this:
>
> def MyFunc(self,clsProperty):
>    if clsProperty.Private:
>         print 'Private property'
>    else:
>         print ClsProperty.Value

This method does not use `self` at all, and that's rather suspicious for  
an instance method.
And you set properties on the class itself? So you never create instances  
of that class?

> In our code, we then call
>>>> MyClass.MyFunc(MyClass.Phone)
>
> We want to be able in our code instead simply to call:
>>>> MyClass.MyFunc(Phone) or MyClass.MyFunc('Phone')
>
> But we can't get it to work. If we rewrite the function as follows:
>
> def MyFunc(self,attr):
>    if self.attr.Private:
>       print 'Private'
>    else:
>       print self.attr.Value
>
> we get an error.

Surely an AttributeError, because you dont have any attribute named "attr".
Notice that on this version you are using `self`, but on the above version  
you didnt use it.
There are easy ways in Python to access an attribute by name, but I think  
that this would just add more noise to your code. Please tell us about  
your design, or rethink it. Do actually exist instances of MyClass, or  
not? I can imagine "Phone" being an attribute of a certain instance of  
Person, by example, but not a class attribute.

> Is there a better way to do this? Thanks
Surely, but we need to know your goal, what do you really want to do, not  
how do you think you should do that.

-- 
Gabriel Genellina




More information about the Python-list mailing list