Python封装类方法代码输出出现None的原因问询
None? Let's break down exactly why that extra None is showing up in your output. First, here's your code for reference:
class encap: __a = 10 b=11 def __abc(self): print(self.b) print(self.__a) def xyz (self): # calling private method self.__abc() a1= encap() print(a1.xyz())
You already understand why 11 and 10 are printed—those come directly from the print statements inside your private __abc() method, which gets triggered when xyz() runs.
The None is caused by this specific line:
print(a1.xyz())
In Python, any function or method that doesn't have an explicit return statement automatically returns None by default. Your xyz() method only calls __abc() and doesn't return any value of its own. So when you pass a1.xyz() to print(), you're telling Python to print the return value of xyz()—which is that default None.
Fix it in two simple ways:
Option 1: Skip wrapping the method call in
print()
Since theprintlogic is already handled inside__abc(), just call the method directly:a1 = encap() a1.xyz() # Output will be 11, then 10 (no extra None)Option 2: Add an explicit
returntoxyz()
If you wantxyz()to return a meaningful value instead ofNone, define what it should send back:def xyz(self): self.__abc() return "Method executed successfully" # Custom return valueNow
print(a1.xyz())will print11,10, and your custom message instead ofNone.
内容的提问来源于stack exchange,提问作者Anubhav Srivastava

