簡體   English   中英

如何在 python 中向 class 添加屬性

[英]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 引用,但不能直接通過實例引用。

你可以參考這個https://www.tutorialspoint.com/class-or-static-variables-in-python#:~:text=When%20we%20declare%20a%20variable,not%20directly%20through%20an%20instance .

有兩種方法可以為 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM