[英]How to add attribute to class in python
I have:我有:
class A:
a=1
b=2
I want to make as我想做
setattr(A,'c')
then all objects that I create it from class A
has c
attribute.然后我从class A
创建的所有对象都具有c
属性。 i did not want to use inheritance我不想使用 inheritance
Just add this line to your code:只需将此行添加到您的代码中:
A.c = 3
And then if you do:然后如果你这样做:
print(A.c)
It will output:它将 output:
3
You can you static or class variables.您可以使用 static 或 class 变量。
You can do A.c in your Code.您可以在代码中执行 A.c。
When we declare a variable inside a class but outside any method, it is called as class or static variable in python.当我们在 class 但在任何方法之外声明一个变量时,它在 Z23EEEB4347BDD26BDDZB6EE.7 中称为 class 或 static 变量Class or static variable can be referred through a class but not directly through an instance. Class 或 static 变量可以通过 class 引用,但不能直接通过实例引用。
You can refer this https://www.tutorialspoint.com/class-or-static-variables-in-python#:~:text=When%20we%20declare%20a%20variable,not%20directly%20through%20an%20instance .你可以参考这个https://www.tutorialspoint.com/class-or-static-variables-in-python#:~:text=When%20we%20declare%20a%20variable,not%20directly%20through%20an%20instance .
There're two ways of setting an attribute to your class;有两种方法可以为 class 设置属性;
First, by using setattr(class, variable, value)首先,通过使用setattr(class, variable, value)
Code Syntax代码语法
setattr(A,'c', 'c')
print(dir(A))
OUTPUT OUTPUT
You can see the structure of the class A within attributes您可以在属性中看到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]
Second, you can do it simply by assigning the variable其次,您可以简单地通过分配变量来做到这一点
Code Syntax代码语法
A.d = 'd'
print(dir(A))
OUTPUT OUTPUT
You can see the structure of the class A within attributes您可以在属性中看到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.