新聞中心
這里有您想知道的互聯(lián)網營銷解決方案
創(chuàng)新互聯(lián)Python教程:Python setattr()
內置函數(shù)setattr()用于將給定值賦給指定對象的指定屬性。

創(chuàng)新互聯(lián)主要從事成都做網站、成都網站建設、成都外貿網站建設、網頁設計、企業(yè)做網站、公司建網站等業(yè)務。立足成都服務明水,10余年網站建設經驗,價格優(yōu)惠、服務專業(yè),歡迎來電咨詢建站服務:028-86922220
**setattr(object, name, value)** #where object indicates whose attribute value is needs to be changesetattr()參數(shù):
取三個參數(shù)。我們可以說setattr()相當于 object.attribute = value。
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| 目標 | 必須設置其屬性的對象 | 需要 |
| 名字 | 屬性名 | 需要 |
| 價值 | 該值被賦予該屬性 | 需要 |
setattr()返回值
setattr()方法不返回任何東西,它只分配對象屬性值。這個函數(shù)在動態(tài)編程中很有用,在這種情況下,我們不能使用“點”運算符來分配屬性值。
Python 中setattr()方法的示例
示例setattr()在 Python 中是如何工作的?
class PersonName:
name = 'Dany'
p = PersonName()
print('Before modification:', p.name)
# setting name to 'John'
setattr(p, 'name', 'John')
print('After modification:', p.name)
輸出:
Before modification: Dany
After modification: John示例 2:當在setattr()中找不到屬性時
class PersonName:
name = 'Dany'
p = PersonName()
# setting attribute name to John
setattr(p, 'name', 'John')
print('Name is:', p.name)
# setting an attribute not present in Person
setattr(p, 'age', 23)
print('Age is:', p.age)
輸出:
Name is: John
Age is: 23示例 3: Python setattr()異常情況
class PersonName:
def __init__(self):
self._name = None
def get_name(self):
print('get_name called')
return self._name
# for read-only attribute
name = property(get_name, None)
p = PersonName()
setattr(p, 'name', 'Sayooj')
輸出:
Traceback (most recent call last):
File "/Users/sayooj/Documents/github/journaldev/Python-3/basic_examples/python_setattr_example.py", line 39, in setattr(p, 'name', 'Sayooj')
AttributeError: can't set attribute 網頁名稱:創(chuàng)新互聯(lián)Python教程:Python setattr()
文章起源:http://m.fisionsoft.com.cn/article/djpdpsi.html


咨詢
建站咨詢
