Dec-26-2023, 03:43 PM
(This post was last modified: Dec-26-2023, 04:29 PM by deanhystad.)
Looks like a descriptor is an object that returns a value when referenced. This differs from most objects that return themselves when referenced. The returned value is the result of a computation. Your example could be written to use a method instead of a descriptor.
As the article goes on to discuss, a property is a kind of descriptor.
A property is different than an instance variable in that it executes code to get the value. You could not do this.
Putting print statements in methods is usually a bad idea, unless the method is only used for the side effect of printing to output
import os class Directory: def __init__(self, dirname): self.dirname = dirname # Regular instance attribute def size(self): return len(os.listdir(self.dirname)) s = Directory(".") print(s.size())Notice that size is a method and must be called.
As the article goes on to discuss, a property is a kind of descriptor.
import os class Directory: def __init__(self, dirname): self.dirname = dirname # Regular instance attribute @property def size(self): return len(os.listdir(self.dirname)) s = Directory(".") print(s.size)Notice that the property size is referenced like an instance variable even though it executes a method when referenced. The main difference between a property and a descriptor is that a property is an attribute of a class, but a descriptor is a standalone object.
A property is different than an instance variable in that it executes code to get the value. You could not do this.
import os class Directory: def __init__(self, dirname): self.dirname = dirname # Regular instance attribute self.size = len(os.listdir(self.dirname)) s = Directory(".") print(s.size) os.remove('somefile.txt') print(s.size)In this example the directory size is not recomputed, so size remains the initial size of the directory and doesn't change to show the new size after the file is removed.
Quote:how can I change the __get__ method to show(print at output) what is self and what is obj and what is objtype,namely for s=directory(..), output shows size and s and DirectoryYou could add a print statment to the method.
class DirectorySize: def __get__(self, obj, objtype=None): print(self, obj, objtype) return len(os.listdir(obj.dirname))The print statement will show you that self is a DirectorySize object and obj is a Directory object (s or g in your example).
Putting print statements in methods is usually a bad idea, unless the method is only used for the side effect of printing to output