英文:
GEtting Error: Attribute error class object has no attribute
问题
我相对于Python和面向对象编程比较新。我一直在尝试创建一个根据该函数的输入创建类的函数。我假设类和对象已经创建,因为我没有收到错误。问题是,当我尝试通过它的属性访问一个字段时,我得到了"AttributeError: 'Class' object has no attribute..."的错误,并且不知道原因。这个问题的方法有什么问题吗?任何帮助将不胜感激。
**代码:**
def make_class(*args):
class Class:
def init(self, *args):
for i, e in enumerate(args):
setattr(self, "{}".format(e), e)
return Class
Animal = make_class("name", "species", "age", "health", "weight", "color")
dog1 = Animal("Bob", "Dog", 5, "good", "50lb", "brown")
dog1.name
**错误**
Traceback (most recent call last):
File "<pyshell#112>", line 1, in
dog1.name
AttributeError: 'Class' object has no attribute 'name'
<details>
<summary>英文:</summary>
I am relatively new to python and to OOP. I have been trying to create a function that creates a class based on the inputs of said function. I assume the class and the object are created since I get no errors. The thing is that when I try to access a field by its attribute i get the "AttributeError: 'Class' object has no attribute...", and can catch why. Is there something wrong with the approach to the problem? Any help is appreciated.
**CODE:**
def make_class(*args):
class Class:
def init(self,*args):
for i,e in enumerate(args):
setattr(self, "{}".format(e), e)
return Class
Animal=make_class("name", "species", "age", "health", "weight", "color")
dog1=Animal("Bob","Dog",5,"good","50lb","brown")
dog1.name
**ERROR**
Traceback (most recent call last):
File "<pyshell#112>", line 1, in <module>
dog1.name
AttributeError: 'Class' object has no attribute 'name'
</details>
# 答案1
**得分**: 0
问题在于您在`make_class()`和`__init__()`的参数中都使用了相同的名称`args`。您的代码只使用了`__init__()`的参数。
您应该同时迭代两个参数列表,因此它们需要不同的名称。
```python
def make_class(*attr_names):
class Class:
def __init__(self, *args):
for name, value in zip(attr_names, args):
setattr(self, name, value)
return Class
英文:
The problem is that you're using the same name args
for the arguments to make_class()
and __init__()
. Your code is just using the __init__()
arguments.
You should iterate over the two argument lists in parallel, so they need different names.
def make_class(*attr_names):
class Class:
def __init__(self,*args):
for name, value in zip(attr_names, args):
setattr(self, name, value)
return Class
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论