Python 的类

                     

贡献者: addis

  • 本词条处于草稿阶段.

  

未完成:类和继承参考这里,算符重载参考这里

1. 基础

# 定义 person 类
class person(): # 括号可以省略
    def __init__(self, name, age): # 构造函数(只能有一个)
        self.name = name 
        self.age = age 
    def show(self): 
        print("name is", self.name ) 
        print("age is", self.age ) 

# 生成对象
p1 = person("jason", "30") 
p2 = person("justin", "28")

# 调用成员函数
p1.show();
p2.show();
运行结果
name is jason
age is 30
name is justin
age is 28

   来定义一个平面点类

class point:
    """这里是 point.__doc__ 的内容"""
    def __init__(self, x, y): 
        self.x = x 
        self.y = y 
    def __str__(self): # 用于 print()
        return "({0}, {1})".format(self.x, self.y)
    def __repr__(self): # 用于不加自动显示内容, 也可以用 repr(obj) 直接调用
        return __str__(self)
    def __add__(self, other): # 算符 +, self 必须是第一个变量
        if isinstance(other, point):
            return point(self.x + other.x, self.y + other.y)
        else:
            return point(self.x + other, self.y + other)
    @property # 调用可以直接用 p.len, 省略括号
    def len(self):
        return self.x**2 + self.y**2

2. 算符重载

3. 继承

                     

© 小时科技 保留一切权利