面向对象

继承

单继承

class A:
    def f(self):
        print('A.f()')


class B(A):
    def f(self):
        print('B.f()')


class C(B):
    pass


c = C()
c.f()

# 输出
B.f()

多继承

class A:
    def f(self):
        print('A.f()')


class B:
    def f(self):
        print('B.f()')


class C(A, B):
    pass


c = C()
c.f()

私有

#!/usr/bin/python3

class JustCounter:
    __secretCount = 0  # 私有变量
    publicCount = 0    # 公开变量

    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print (self.__secretCount)

counter = JustCounter()
counter.count()
counter.count()
print (counter.publicCount)
print (counter.__secretCount)  # 报错,实例不能访问私有变量
#!/usr/bin/python3

class Site:
    def __init__(self, name, url):
        self.name = name       # public
        self.__url = url   # private

    def who(self):
        print('name  : ', self.name)
        print('url : ', self.__url)

    def __foo(self):          # 私有方法
        print('这是私有方法')

    def foo(self):            # 公共方法
        print('这是公共方法')
        self.__foo()

x = Site('菜鸟教程', 'www.runoob.com')
x.who()        # 正常输出
x.foo()        # 正常输出
x.__foo()      # 报错

类的专有方法

  • __init__ : 构造函数,在生成对象时调用

  • __del__ : 析构函数,释放对象时使用

  • __repr__ : 打印,转换

  • __setitem__ : 按照索引赋值

  • __getitem__: 按照索引获取值

  • __len__: 获得长度

  • __cmp__: 比较运算

  • __call__: 函数调用

  • __add__: 加运算

  • __sub__: 减运算

  • __mul__: 乘运算

  • __div__: 除运算

  • __mod__: 求余运算

  • __pow__: 乘方

    运算符重载

#!/usr/bin/python3

class Vector:
   def __init__(self, a, b):
      self.a = a
      self.b = b

   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)

   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)

最后更新于

这有帮助吗?