我似乎找不到有关此事的确切答案,我想原因是因为这取决于情况。

问题描述 投票:0回答:0

或带有“私有”属性的多个设置器/获取器:

class A: # Name mangling issues? def __init__(self, a, b, c): self.__a = a self.__b = b self.__c = c def set_a(self, a): self.__a = a def get_a(self): return self.__a def set_b(self, b): self.__b = b def get_b(self): return self.__b ... # (same for c)

或通用设置器/Getters:

class A: # Less cluttered, but less intuitive that attributes are meant to be "private"? def __init__(self, a, b, c): self.a = a self.b = b self.c = c def __getattr__(self, name: str): return self.__dict__[f"_{name}"] def __setattr__(self, name, value): self.__dict__[f"_{name}"] = value

或Python描述符? (如果B和C共享某些相似之处,那将看起来像是B和C的样子?)。
thanks!

首先:Python中没有什么是私人的;如果您尽力而为,可以更改字面数字
2
表示三个。

,但是,您可以使编辑属性更加困难,并清楚地表明它们并不是要编辑的。有几种方法可以实现这一目标。以下是我的最爱之一。实现生产代码并提出了重点很简单。

class MyClass: def __init__(self, name, age): self._name = name # private attribute self._age = age # private attribute # Custom __setattr__ to prevent setting private attributes def __setattr__(self, name, value): if name.startswith('_'): # Check if it's a private attribute raise AttributeError(f"Cannot modify private attribute '{name}'") else: super().__setattr__(name, value) obj = MyClass("Alice", 30) # valid usage obj._name = "Bob" # raises error print(obj._name) # prints "Alice" so you can still access the names in the class easily
    

python python-3.x class oop python-descriptors
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.