0

I have a very similar question to this except I would like to name my function property

so for example Id like to do something like:

class ThingWithProperties(object): def property(self, a): print("in property", a) @property def test(self): print("in test") t = Testing() t.property(1) t.test() 

But I get the following error:

Traceback (most recent call last): File "test.py", line 5, in <module> class ThingWithProperties(object): File "test.py", line 10, in ThingWithProperties @property TypeError: property() missing 1 required positional argument: 'a' 

Could someone please explain why this is happening? As well as how to work around it (without renaming my instance method)?

3
  • 1
    Try defining your property method after all the usage of the decorator are done in the scope of the definition of that class. I.e. define test before property. Commented Nov 12, 2015 at 2:28
  • You really should rename your instance method. Commented Nov 12, 2015 at 2:45
  • I am going to rename it. I just wanted to know why it was being shadowed and the other question got nothing but answers saying "just rename it" Commented Nov 12, 2015 at 3:09

1 Answer 1

3

This is happening because by defining a method called property, you are shadowing the builtin property within the scope of the class declaration. Hence when you write @property, your method is called to decorate test as opposed to the builtin property.

You could use the __builtin__ module to explicitly use the builtin property:

class ThingWithProperties(object): def property(self, a): print("in property", a) @__builtin__.property def test(self): print("in test") 

Though I personally always avoid shadowing builtins, even if they are only shadowed in a limited scope, as is the case here.


To be a little more clear about the "shadowing" going on, try running this in your interpreter:

foo = 42 print(foo) class Test: foo = 73 print(foo) print(foo) 

There are two points to make here: First, some might be surprised that we can print things in a class definition. The point is that a class definition is a code block like any other, and you can write for-loops and print all you'd like, and whatever variables or functions you create are gathered together into a class dictionary when it comes time to actually create the class.

The second point is that the class definition creates a new scope, and the value of foo inside the scope is different than outside. That is, the above prints 42, then 73, then 42 again.

Sign up to request clarification or add additional context in comments.

1 Comment

I also "always avoid shadowing builtins, even if they are only shadowed in a limited scope, as is the case here."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.