當你創建一個用戶定義的類時,默認情況下,你可以動態地向它添加屬性,就像在下一個示例中一樣:
# User defined class
class Test:
def __init__(self):
self.first_att = 5
test = Test()
test.second_att = 11
print(test.__dict__)
{'first_att': 5, 'second_att': 11}
但是內置類不允許這樣的事情:
# Built-in class
str_example = 'Test string'
str_example.added_att = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'added_att'
如何修改我的類 Test 以使其也不允許?提前致謝
uj5u.com熱心網友回復:
您可以通過覆寫該__setattr__方法來實作。作為您案例的一個非常簡單的示例
class Test:
def __init__(self):
self.first_att = 5
def __setattr__(self, key, value):
if key != "first_att":
raise AttributeError(f"Not allowed to set attribute {key}")
super().__setattr__(key, value)
請注意,您必須在此處將例外串列添加到您希望能夠為其分配值的屬性。
uj5u.com熱心網友回復:
您可以通過添加在您的類中定義允許的屬性__slots__。
在那里放置您想要的屬性的名稱。不接受所有其他屬性。
例如試試這個:
# User defined class
class Test:
__slots__ = ("fitst_att", "your_att_name")
def __init__(self):
self.first_att = 5
test = Test()
test.your_att_name = 11
print(test.__dict__)
# test.second_att = 11 ##this will rais an error
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/419876.html
標籤:
下一篇:Python資料框串列-列拆分
