Im trying to create a class with some formatting options. But i can’t figure out how to do it properly…
The code produced the following error:
AttributeError: ‘NoneType’ object has no attribute ‘valuesonly’
class Testings(object):
def format_as_values_only(self,somedata):
buildstring=somedata.values()
return buildstring
def format_as_keys_only(self):
pass
def format_as_numbers(self):
pass
def get_data_method(self):
self.data= {'2_testkey':'2_testvalue',"2_testkey2":"2_testvalue2"}
@property
def valuesonly(self):
return format_as_values_only(self.data)
test=Testings()
print test.get_data_method().valuesonly
The important thing for me is to be able to get the formatters like: class.method.formatter or so…
Thanks a lot for any hints!
You can’t do things this way. Methods are just functions defined directly inside a class block. Your function is inside another function, so it’s not a method. The
propertydecorator is useless except in a class block.But, more fundamentally, function definitions just create local names, the same as variable assignments or anything else. Your
valuesonlyfunction is not accessible at all from outside theget_data_methodfunction, because nothing from within a function is accessible except its return value. What you have done is no different than:. . . and then expecting to be able to access the local variable
afrom outside the function. It won’t work. When you callget_data_method(), you get the valueNone, becauseget_data_methoddoesn’t return anything. Anything you subsequently do with the result ofget_data_method()is just operating on that same None value.If you want to access things using the syntax you describe, you will need to make
get_data_methodreturn an object that has properties likevaluesonly. In other words, write another class that provides avaluesonlyproperty, and haveget_data_methodreturn an instance of that class. A rough outline (untested):However, you should think about why you want to do this. It’s likely to be simpler to set it up to just call
valuesonlydirectly on theTestingobject, or to pass a flag toget_data_method, doing something likeget_data_method(valuesonly=True).