Python类方法内检测伪私有属性是否存在的更优方法咨询
Hey there! Great question about handling private attribute checks inside a Python class. Let's break down some simpler alternatives to your current approach.
1. Use a try-except Block (Most Straightforward & Idiomatic)
Since inside the class, Python automatically resolves the name mangling for __a when you access it directly, you can simply attempt to access the attribute and catch an AttributeError if it doesn't exist. This avoids having to manually construct the mangled attribute name entirely, and follows Python's "Easier to ask for forgiveness than permission" (EAFP) principle.
class A: def __init__(self): self.__a = 5 def hasAttr(self): try: # Just attempt to access the attribute (we don't need to use its value) _ = self.__a print(True) except AttributeError: print(False) x = A() x.hasAttr() # Prints True
2. Use hasattr with Dynamically Generated Mangled Name
If you prefer using hasattr explicitly, you can dynamically generate the mangled name without hardcoding your class name. This is cleaner than manually checking __dict__ since hasattr is purpose-built for attribute existence checks:
class A: def __init__(self): self.__a = 5 def hasAttr(self): # Dynamically create the mangled name using the class's own name mangled_attr = f'_{self.__class__.__name__}__a' print(hasattr(self, mangled_attr)) x = A() x.hasAttr() # Prints True
Why Your Initial hasattr(self, '__a') Failed
To quickly recap: Python performs name mangling on attributes starting with two underscores, renaming them to _ClassName__attribute to prevent accidental external access. When you pass the raw string '__a' to hasattr, it looks for exactly that un-mangled name, which doesn't exist in the instance's attribute dictionary.
Quick Recommendation
The try-except approach is the best choice here—it's concise, avoids messing with name mangling logic, and aligns with standard Python coding practices.
内容的提问来源于stack exchange,提问作者Ayoub ZAROU

