python 之面向对象

class MyClass(object):

    
# Static Field 静态字段
    count = 0

  
# Constructor 构造函数,与c#的不同,他的名称不是以类的名称作为构造函数的名称,而是init
    def __init__(self, x = 1):
        self.
__x = x # Instance Private Field

    
# Private Instance Method 定义私有函数 self 与c#的 this基本相同
    def __print(self, s):
        
print (s)

    
# Instance Method  实例化方法 test 
    def test(self):
        self.
__print("Instance method call")

    
# Static Method    表态方法 @staticmethod 
    @staticmethod
    
def stest():
        
print ("Static Method")

    
# Property get()   属性get @property
    @property
    
def x(self):
        
return self.__x

    
# Property set() 属性set @property
    @x.setter
    
def x(self, value):
        self.
__x = value

    
# Operator Overloading  操作符重载,实现对象与对象之间的操作
    def __add__(self, o):
        
return MyClass(self.x + o.x)
    
def main():
    o 
= MyClass(123)
    
    o.x 
= 456
    
print (o.x)

    o.test()
    MyClass.stest()

    s 
= o + MyClass(321)
    
print (s.x)
      
if __name__ == "__main__":
    main()

上面介召如何申明    私有成员方法

                           公开成员方法

                           静态方法

                           属性get

                           属性set

                          构造方法

                          及操作符重载

                          类指针操作符self==(c#.this)

                                                        等常规面向对象的使用方式。

原文地址:https://www.cnblogs.com/chenli0513/p/1875493.html