简体   繁体   English

使用 __init__ 方法更新对象的实例

[英]Updating an instance of an object with the __init__ method

Reusing the __init__<\/code> method to change attributes' values重用__init__<\/code>方法来改变属性的值<\/h3>

Python 3.10 on Windows 64bit<\/em> Windows 64 位上的 Python 3.10<\/em>

Let's say I have a class that has an update<\/code> method which calls the __init__<\/code> method.假设我有一个类,它有一个调用__init__<\/code>方法的update<\/code>方法。 The update<\/code> method is created to avoid multiple line assignments of the attributes.创建update<\/code>方法是为了避免属性的多行分配。

 class Person: def __init__(self, name: str, age: int): self.name = name self.age = age def update(self, **attributes): self.__init__(**attributes)<\/code><\/pre>

Object instantiation:<\/strong>对象实例化:<\/strong>

 p = Person(name="Alex", age=32) print(p.name, p.age) >> Alex 32<\/code><\/pre>

Object reference before:<\/strong>之前的对象参考:<\/strong>

 print(p) >> <__main__.Person object at 0x0000028B4ED949A0><\/code><\/pre>

Calling for the update method:<\/strong>调用更新方法:<\/strong>

 p.update(name="Sam", age=80) print(p.name, p.age) >> Sam 80<\/code><\/pre>

Object reference after:<\/strong>之后的对象引用:<\/strong>

 print(p) >> <__main__.Person object at 0x0000028B4ED949A0><\/code><\/pre>

Clearly, the reference hasn't changed!<\/strong>显然,参考没有改变!<\/strong>

Is this safe?这安全吗? Is there a chance where the object reference in memory gets changed?内存中的对象引用是否有可能被更改?<\/h4>

Obviously the actual use of this is for large objects that has multiple parameters and get frequently modified at once as internal reactions.显然,它的实际用途是用于具有多个参数并且作为内部反应一次频繁修改的大型对象。 Some parameters are optional and don't get modified.一些参数是可选的,不会被修改。

If I don't do it like this, I would have to write a cascade of if-else statements which I don't want to.<\/em>如果我不这样做,我将不得不编写一系列我不想写的 if-else 语句。<\/em> :)<\/em> :)<\/em>

"

__init__<\/code> , unlike __new__<\/code> , doesn't deal with memory references at all. __init__<\/code>与__new__<\/code>不同,根本不处理内存引用。 self<\/code> is already a valid object produced by __new__<\/code> which __init__<\/code> initializes. self<\/code>已经是由__init__<\/code>初始化的__new__<\/code>生成的有效对象。

You can do it the other way round for clarity:为了清楚起见,您可以反过来做:

class Person:
     def __init__(self, name: str, age: int):
         # Signal to whoever will read your code
         # that the class is supposed to have these attributes
         self.name = None
         self.age = None
         self.update(name=name, age=age)

     def update(self, name: str, age: int):
         self.name = name
         self.age = age

in addition to ForceBru's answer if wanted如果需要的话,除了 ForceBru 的回答

class Person:
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

    def update(self, **attributes):
        for attribute, value in attributes.items():
            if hasattr(self,attribute):
                setattr(self, attribute, value)
            else:
                raise AttributeError(f'{self.__name__} has no attribute: {attribute}')
        
x = Person(name='Henry',age=12)
print(f'name={x.name}, age={x.age}')
x.update(name='Joe')
print(f'name={x.name}, age={x.age}')
x.update(name='Kyle',age=20)
print(f'name={x.name}, age={x.age}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM