Python Forum

Full Version: question about __slots__
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi
in the code:( address of the code is line 2)
# usage of slot to prevent of dynamical attribute change by user.
# https://realpython.com/python-mutable-vs-immutable-types/#techniques-to-
# control-mutability-in-custom-classes

class Book:
    __slots__=("title",)
    def __init__(self,title):
        self.title=title

harry_potter = Book("Harry Potter")
# there is 'title' in results of two below command
print(f"dir(Book): {dir(Book)}")
print(f"dir(harry_potter): {dir(harry_potter)}")



del harry_potter.title   # remove 'title' attribute
# but there is 'title' in dir(Book) and dir(harry_potter):
print(f"\t result of del harry_potter.title")
print(f"dir(Book): {dir(Book)}")       # 'title is in dir(Book)
print(f"dir(harry_potter): {dir(harry_potter)}")   # 'title' is in dir(harry_potter)

# but the result of the below command is an error:
harry_potter.title
# result of the above  line is:AttributeError: 'Book' object has no attribute 'title'
after delteing title attribute from harry_potter in line 17, there is the title attribute in dir(Book) and dir(harry_potter), but the result of
harry_potter.title
(line 24) is an error.
how is it possible that there is title attribute in harry_potter but the result of the mentioned command is an error?
thanks
I think the answer is in the dir's function documentation. The dir() function includes the attributes of the object's type in the list that it returns, so 'title' is mentioned in dir(harry_potter) because it is an attribute of the Book class.

I don't know how this behavior is implemented. The answer is in the fine details of attribute access in Python's C source code.

Python documentation Wrote:Note Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.