python面向对象类代码示例_python面向对象代码示例

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# a class definition

class MyClass:

"""一个简单的类定义 A Simple Example Class"""

i = 1234 #类的成员变量

def f(self):#类的成员函数

return "Hello World"

x = MyClass()

print MyClass.__doc__

print x.__doc__

#显示定义一个类的初始化方法

class Complex:

def __init__(self, realpart, imagpart):

self.r = realpart

self.i = imagpart

x = Complex(3.0, -4.5)

print x.r, x.i

x.counter = 2 #instance attribute

print x.counter # print Complex.counter将出错

del x.counter

#类的成员函数也可以在外部定义

def f1(self, x, y):

return min(x, x+y)

class C:

f = f1

def g(self):

return 'hello world'

h = g

#这样C.f C.h C.g都是合法的函数对象

#在类的函数定义中,可以使用self引用类的其他成员变量或函数对象

class Bag:

def __init__(self):

self.data = []

def add(self, x):

self.data.append(x)

def addtwice(self, x):

self.add(x)

self.add(x)

#继承与多重继承

class BaseClassName:

pass

class DerivedClass(BaseClassName):

pass

class BaseClassName2:

pass

class DerivedClass2(BaseClassName, BaseClassName2):

pass

#实用方法isintance issubclass

d = DerivedClass2()

print isinstance(d, BaseClassName)

print issubclass(DerivedClass2, BaseClassName2)

#私有变量

#在python中,没有真正意义上的私有概念,一般约定命名中以下划线开头的变量或函数为私有的。

class Mapping:

def __init__(self, iterable):

self.items_list = []

self.__update(iterable)

def update(self, iterable):

for item in iterable:

self.items_list.append(item)

__update = update # private copy of original update() method

class MappingSubclass(Mapping):

def update(self, keys, values):

# provides new signature for update()

# but does not break __init__()

for item in zip(keys, values):

self.items_list.append(item)

#类似C中的结构体的使用

class Employee:

pass

john = Employee() # Create an empty employee record

# Fill the fields of the record

john.name = 'John Doe'

john.dept = 'computer lab'

john.salary = 1000

#在python中,用户自定义的异常也被认为是类

#有两种形式raise Class, instance 和 raise instance

class B:

pass

class C(B):

pass

class D(C):

pass

for c in [B, C, D]:

try:

raise c()

except D:

print "D"

except C:

print "C"

except B:

print "B"

#迭代器的实现

class Reverse:

"""Iterator for looping over a sequence backwards."""

def __init__(self, data):

self.data = data

self.index = len(data)

def __iter__(self):

return self

def next(self):

if self.index == 0:

raise StopIteration

self.index = self.index - 1

return self.data[self.index]

rev = Reverse('spam')

for char in rev:

print char

#产生器

def reverse(data):

for index in range(len(data)-1, -1, -1):

yield data[index]

for char in reverse('golf'):

print char

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值