#!/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)
python面向对象代码示例
最新推荐文章于 2024-06-21 15:26:30 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)