[英]How to add attribute to class in python
我有:
class A:
a=1
b=2
我想做
setattr(A,'c')
然后我從class A
創建的所有對象都具有c
屬性。 我不想使用 inheritance
只需將此行添加到您的代碼中:
A.c = 3
然后如果你這樣做:
print(A.c)
它將 output:
3
您可以使用 static 或 class 變量。
您可以在代碼中執行 A.c。
當我們在 class 但在任何方法之外聲明一個變量時,它在 Z23EEEB4347BDD26BDDZB6EE.7 中稱為 class 或 static 變量 Class 或 static 變量可以通過 class 引用,但不能直接通過實例引用。
有兩種方法可以為 class 設置屬性;
首先,通過使用setattr(class, variable, value)
代碼語法
setattr(A,'c', 'c')
print(dir(A))
OUTPUT
您可以在屬性中看到class A的結構
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__le__', '__lt__', '__module__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'__weakref__', 'a', 'b', 'c']
[Program finished]
其次,您可以簡單地通過分配變量來做到這一點
代碼語法
A.d = 'd'
print(dir(A))
OUTPUT
您可以在屬性中看到class A的結構
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__le__', '__lt__', '__module__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'__weakref__', 'a', 'b', 'c', 'd']
[Program finished]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.