Python中的面向对象编程| Set 2(数据隐藏和对象打印)
先决条件: Python中的面向对象编程 |第 1 组(类、对象和成员)
数据隐藏
在Python中,我们在属性名称前使用双下划线(或 __),这些属性在外部不会直接可见。
Python
class MyClass:
# Hidden member of MyClass
__hiddenVariable = 0
# A member method that changes
# __hiddenVariable
def add(self, increment):
self.__hiddenVariable += increment
print (self.__hiddenVariable)
# Driver code
myObject = MyClass()
myObject.add(2)
myObject.add(5)
# This line causes error
print (myObject.__hiddenVariable)
Python
# A Python program to demonstrate that hidden
# members can be accessed outside a class
class MyClass:
# Hidden member of MyClass
__hiddenVariable = 10
# Driver code
myObject = MyClass()
print(myObject._MyClass__hiddenVariable)
Python
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "Test a:%s b:%s" % (self.a, self.b)
def __str__(self):
return "From str method of Test: a is %s," \
"b is %s" % (self.a, self.b)
# Driver Code
t = Test(1234, 5678)
print(t) # This calls __str__()
print([t]) # This calls __repr__()
Python
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "Test a:%s b:%s" % (self.a, self.b)
# Driver Code
t = Test(1234, 5678)
print(t)
Python
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
# Driver Code
t = Test(1234, 5678)
print(t)
输出 :
2
7
Traceback (most recent call last):
File "filename.py", line 13, in
print (myObject.__hiddenVariable)
AttributeError: MyClass instance has
no attribute '__hiddenVariable'
在上面的程序中,我们尝试使用对象访问类外部的隐藏变量,它抛出了异常。
我们可以通过一种复杂的语法访问隐藏属性的值:
Python
# A Python program to demonstrate that hidden
# members can be accessed outside a class
class MyClass:
# Hidden member of MyClass
__hiddenVariable = 10
# Driver code
myObject = MyClass()
print(myObject._MyClass__hiddenVariable)
输出 :
10
私有方法可以在它们的类之外访问,只是不容易访问。 Python中没有什么是真正私有的。在内部,私有方法和属性的名称会在运行中被修改和取消修改,以使它们看起来无法通过它们的给定名称访问[参见this for source]。
打印对象
打印对象为我们提供了有关我们正在使用的对象的信息。在 C++ 中,我们可以通过为类添加一个友元 ostream&运算符<< (ostream&, const Foobar&) 方法来做到这一点。在Java中,我们使用 toString() 方法。
在Python中,这可以通过使用 __repr__ 或 __str__ 方法来实现。
Python
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "Test a:%s b:%s" % (self.a, self.b)
def __str__(self):
return "From str method of Test: a is %s," \
"b is %s" % (self.a, self.b)
# Driver Code
t = Test(1234, 5678)
print(t) # This calls __str__()
print([t]) # This calls __repr__()
输出 :
From str method of Test: a is 1234,b is 5678
[Test a:1234 b:5678]
关于印刷的要点:
- 如果没有定义 __str__ 方法,则 print t(或 print str(t))使用 __repr__。
Python
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "Test a:%s b:%s" % (self.a, self.b)
# Driver Code
t = Test(1234, 5678)
print(t)
输出 :
Test a:1234 b:5678
- 如果没有定义 __repr__ 方法,则使用默认值。
Python
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
# Driver Code
t = Test(1234, 5678)
print(t)
输出 :
<__main__.Test instance at 0x7fa079da6710>