类的应用

class Y:
    def __init__(self, v0):
        self.v0 = v0
        self.g = 9.81
    def value(self, t):
        return self.v0*t - 0.5*self.g*t**2

y = Y(3)
v = y.value(0.1)

more examples on classes:
Bank Accounts

class Account:
    def __init__(self, name, account_number, initial_amount):
        self.name = name
        self.no = account_number
        self.balance = initial_amount
    def deposit(self, amount):
        self.balance += amount
    def withdraw(self, amount):
        self.balance -= amount
    def dump(self):
        s = ’%s, %s, balance: %s’ % \
(self.name, self.no, self.balance)
        print s
>>> from classes import Account
>>> a1 = Account(’John Olsson’, ’19371554951’, 20000)
>>> a2 = Account(’Liz Olsson’, ’19371564761’, 20000)
>>> a1.deposit(1000)
>>> a1.withdraw(4000)
>>> a2.withdraw(10500)
>>> a1.withdraw(3500)
>>> print "a1’s balance:", a1.balance
a1’s balance: 13500
>>> a1.dump()
John Olsson, 19371554951, balance: 13500
>>> a2.dump()
Liz Olsson, 19371564761, balance: 9500

Phone Book

class Person:
    def __init__(self, name,
        mobile_phone=None, office_phone=None,
        private_phone=None, email=None):
        self.name = name
        self.mobile = mobile_phone
        self.office = office_phone
        self.private = private_phone
        self.email = email
    def add_mobile_phone(self, number):
        self.mobile = number
    def add_office_phone(self, number):
        self.office = number
    def add_private_phone(self, number):
        self.private = number
    def add_email(self, address):
        self.email = address

>>> p1 = Person(’Hans Hanson’,
... office_phone=’767828283’, email=’h@hanshanson.com’)
>>> p2 = Person(’Ole Olsen’, office_phone=’767828292’)
>>> p2.add_email(’olsen@somemail.net’)
>>> phone_book = [p1, p2]

A Circle

class Circle:
    def __init__(self, x0, y0, R):
        self.x0, self.y0, self.R = x0, y0, R
    def area(self):
        return pi*self.R**2
    def circumference(self):
        return 2*pi*self.R

>>> c = Circle(2, -1, 5)
>>> print ’A circle with radius %g at (%g, %g) has area %g’ % \
... (c.R, c.x0, c.y0, c.area())
A circle with radius 5 at (2, -1) has area 78.5398
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值