Python 类与面向对象编程基础
1. 类定义基础
在 Python 中,要创建一个类,需要编写类定义。类定义是一组用于定义类的方法和数据属性的语句。以模拟抛硬币程序为例,我们可以创建一个名为 Coin 的类。
import random
# The Coin class simulates a coin that can
# be flipped.
class Coin:
# The __init__ method initializes the
# sideup data attribute with 'Heads'.
def __init__(self):
self.sideup = 'Heads'
# The toss method generates a random number
# in the range of 0 through 1. If the number
# is 0, then sideup is set to 'Heads'.
# Otherwise, sideup is set to 'Tails'.
def toss(self):
if random.randint(0, 1) == 0:
self.sideup = 'Heads'
else:
self.sideup = 'Tails'
# The get_sideup method returns the value
# referenced by
Python类与面向对象入门
超级会员免费看
订阅专栏 解锁全文

11万+

被折叠的 条评论
为什么被折叠?



