Python3 面向对象

2017-03-28  本文已影响0人  Mr_ox

1. 类定义格式

#!/usr/bin/python3

class MyClass:
    """一个简单的类实例"""
    i = 12345
    def f(self):
        return 'hello world'

# 实例化类
x = MyClass()

# 访问类的属性和方法
print("MyClass 类的属性 i 为:", x.i)
print("MyClass 类的方法 f 输出为:", x.f())

2. 构造方法

def _init_():

3. 私有属性

变量命名时在前面加入"__",如__weight = 0

4. 继承

class DerivedClassName(Base1, Base2, Base 3 ...):
    <statement-1>
    .
    <statement-N>

5. 类的专有方法

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

6. 运算符重载

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)
上一篇 下一篇

猜你喜欢

热点阅读