#!/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(BaseC
python面向对象代码示例
最新推荐文章于 2025-10-13 11:58:18 发布
本文通过实例代码介绍了Python面向对象编程的基本概念,包括类的定义、成员变量和函数、初始化方法、实例属性、继承、多态、私有变量、迭代器和生成器的实现。示例涵盖类的创建、实例化、成员访问以及异常处理等。

最低0.47元/天 解锁文章
1077





