Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
question about __slots__
#1
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
Reply


Messages In This Thread
question about __slots__ - by akbarza - Dec-17-2023, 07:10 AM
RE: question about __slots__ - by Gribouillis - Dec-17-2023, 08:02 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Iterate through __slots__ deanhystad 2 3,186 Mar-08-2020, 08:29 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020