在Python中,对象和字典有什么区别?

发布于 2024-11-30 12:42:21 字数 179 浏览 5 评论 0原文

创建对象后,我可以随意添加和删除槽,就像使用字典一样。即使方法也只是存储在槽中的对象,所以我也可以将方法添加到字典中。

我可以用(非字典)对象做一些我永远无法用字典做的事情吗? 或者有没有可能建立一个完全看起来像某个类的对象的字典?

这个问题不是关于它们是如何创建的,而是关于我之后如何使用它们。感谢链接或参考。

After an object has been created, I can add and remove slots at will, as I can do with a dictionary. Even methods are just objects stored in slots, so I probably can add methods to a dictionary as well.

Is there something I can do with a (non-dictionary) object that I could never do with a dictionary?
Or is it possible to set up a dictionary that completely looks like an object of a certain class?

This question is not about how they are created, but about how I can use them afterwards. Links or references are appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

夜雨飘雪 2024-12-07 12:42:21

创建对象后,我可以随意添加和删除槽,就像使用字典一样。甚至方法也只是存储在槽中的对象,

请小心地说槽 -- __slots__ 在 Python 中有特定的含义

所以我可能也可以向字典添加方法。

foo = {}
foo.bar = 1

AttributeError: 'dict' object has no attribute 'bar'

不是默认情况下,您需要对其进行子类化 - 但随后您将使用一个类。相反,将函数放入字典中:

def bar():
    return 1

foo['bar'] = bar
foo['baz'] = lambda: 1

我可以用一个对象做一些我用字典做不到的事情吗?

这个问题实际上有一个错误的前提——字典是对象,所以你对字典所做的任何事情你都是在对一个对象做。对于这个答案的其余部分,当你说“对象”时,我会假装你的意思是“用户定义的类”。

不,对于用户定义的类,没有什么是字典不能做的。类甚至是用字典来实现的。

class Foo(object):
    pass

print Foo.__dict__
# {'__dict__': <attribute '__dict__' of 'Foo' objects>, '__module__': '__main__', 
#      '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None}

任何你能用Python中的类做的事情,你都可以在没有类的情况下完成,但需要做更多的工作(而且代码更难理解、使用和维护)。甚至有人说 Python 类只是字典的语法糖。

最近提出了一个非常类似的问题 我是否需要学习对象,或者我可以节省时间并只学习字典吗? 我认为我对此的回答也与此相关。

After an object has been created, I can add and remove slots at will, as I can do with a dictionary. Even methods are just objects stored in slots,

Be careful saying slots -- __slots__ has a specific meaning in Python.

so I probably can add methods to a dictionary as well.

foo = {}
foo.bar = 1

AttributeError: 'dict' object has no attribute 'bar'

Not by default, you'd need to subclass it -- but then you're using a class. Instead, put the function in the dictionary:

def bar():
    return 1

foo['bar'] = bar
foo['baz'] = lambda: 1

Is there something I can do with an object that I could never do with a dictionary?

This question actually has a false premise -- dictionaries are objects, so anything you do with a dictionary you are doing with an object. For the rest of this answer, I'll pretend you mean "user defined class" when you say "object".

No, there is nothing you can do with a user-defined class you can't do with a dictionary. Classes are even implemented with a dictionary.

class Foo(object):
    pass

print Foo.__dict__
# {'__dict__': <attribute '__dict__' of 'Foo' objects>, '__module__': '__main__', 
#      '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None}

Anything you can do with a class in Python you can do without one, with more work (and code which is much harder to understand, use, and maintain). It's even been said that Python classes are just syntactic sugar for dictionaries.

A very similar question was asked recently as Do I need to learn about objects, or can I save time and just learn dictionaries? I think my answer to that is also relevant here.

独木成林 2024-12-07 12:42:21

当您调用对象的成员函数时,它们会将对象本身作为第一个参数传递。这样它们就可以修改它们所属对象的属性:

class Counter(object):
   def __init__(self):
      self.num = 0

   def inc(self):
      self.num += 1

count = Counter()
count.inc()

如果您只是将一堆函数存储在 dict 中,它们将得不到这样的支持。您必须手动传递字典才能达到相同的效果:

def Counter_inc(d):
   d['num'] += 1

def Counter_create():
   d = {
      'num': 0,
      'inc': Counter_inc,
   }
   return d

count = Counter_create()
count['inc'](count)

正如您所看到的,虽然这是可能的,但它要笨拙得多。虽然您可以使用原始字典模拟对象的许多功能,但对对象的特殊语言支持使它们更易于使用。

还有一些功能直接使用对象类型信息,例如 isinstance()< /a>,它不能轻易地用原始字典复制。

When you call member functions of an object, they get passed the object itself as a first parameter. This way they can modify properties of the object they belong to:

class Counter(object):
   def __init__(self):
      self.num = 0

   def inc(self):
      self.num += 1

count = Counter()
count.inc()

If you just store a bunch of functions in a dict, they will get no such support. You have to pass the dict around manually to achieve the same effect:

def Counter_inc(d):
   d['num'] += 1

def Counter_create():
   d = {
      'num': 0,
      'inc': Counter_inc,
   }
   return d

count = Counter_create()
count['inc'](count)

As you can see while it is possible, it is much more clumsy. While you can emulate many features of object with raw dicts, having special language support for objects makes them easier to use.

Also there are features that directly use an objects type information, like for example isinstance(), which cannot easily be replicated with raw dicts.

丑丑阿 2024-12-07 12:42:21

其他答案有一定道理,但我想补充一点,您不能子类化或实例化特定的字典。

class A(object): pass
class B(A): pass
a = A()

A = {}
B = ???
a = ???

所以,字典是对象,对象主要是用字典实现的(虽然我不知道具体情况),但它们是针对不同工作的不同工具。

The other answers hold some ground, but I'd like to add that you can't subclass or instantiate specific dictionaries.

class A(object): pass
class B(A): pass
a = A()

A = {}
B = ???
a = ???

So, dictionaries are objects and objects are implemented mainly with dictionaries (although I don't know the specifics), but they are different tools for different jobs.

痴意少年 2024-12-07 12:42:21

我想你问的是

o1={"some_method": lambda par1, par2: par1+par2}
o1["some_method"](1, 2)

vs

class SomeClass:
    def some_method(self, par1, par2):
        return par1+par2

o2=SomeClass()
o2.some_method(1, 2)

?如果是这样,我认为从实际角度来看,主要区别在于 o2.some_method 将 self 作为第一个参数,但 o1["some_method"] 不是。

I think you ask about

o1={"some_method": lambda par1, par2: par1+par2}
o1["some_method"](1, 2)

vs

class SomeClass:
    def some_method(self, par1, par2):
        return par1+par2

o2=SomeClass()
o2.some_method(1, 2)

? If so, i think the main differnce from practical point of view, is that o2.some_method takes self as first param but o1["some_method"] not.

空城仅有旧梦在 2024-12-07 12:42:21

对象是从类创建的 {}:

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

student1 = Student('John', 31) # student1 is an object
print(student1) # does not print the expected result, we need to "convert" it to dictionary
print(student1.__dict__) # prints {'name': 'John', 'age': 31}

字典是不是从类创建的 {}:

student2 = { 'name': 'Kevin', age: 15 } # student2 is a dictionary
print(student2) # prints {'name': 'Kevin', 'age': 15}

Object is a {} created from the class:

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

student1 = Student('John', 31) # student1 is an object
print(student1) # does not print the expected result, we need to "convert" it to dictionary
print(student1.__dict__) # prints {'name': 'John', 'age': 31}

Dictionary is a {} not created from the class:

student2 = { 'name': 'Kevin', age: 15 } # student2 is a dictionary
print(student2) # prints {'name': 'Kevin', 'age': 15}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文