AttributeError: 类对象没有属性的错误。

huangapple go评论62阅读模式
英文:

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 &quot;AttributeError: &#39;Class&#39; object has no attribute...&quot;, 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

huangapple
  • 本文由 发表于 2023年2月10日 04:41:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404223.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定