16 python 类基础

1 测试代码

#类定义:用来描述具有相同的属性和方法的对象的集合
class Animal():
    # 定义类变量
    name = ''   # 类变量
    age = 0     # 类变量
    __weight = 0    # 私有变量:子类不能直接使用

    # 定义构造方法:在类实例化时会被自动调用
    def __init__(self,n,a,w):
        self.name = n       # 实例变量
        self.age = a        # 实例变量
        self.__weight = w   # 实例变量(私有变量带两个下划线)

    # 定义方法:
    def speak(self):    # 类方法必须有一个默认参数 self
        occupation = "tester"   # 局部变量
        return "My name is {}, I'm a {}, I'm {} years old, my weight is {}"\
            .format(self.name, occupation, self.age, self.__weight)

    def get_weight(self):           # 获取私有变量的方法
        return self.__weight

    def set_weight(self, weight):   # 设置私有变量的方法
        self.__weight = weight


if __name__ == "__main__":
    animal = Animal('xiaobai', 18, 40)      # 实例化 animal 类
    print(animal.name)      # 调用实例变量
    print(animal.age)       # 调用实例变量
    print(animal.speak())   # 调用方法
    print(animal.get_weight())      # 获取私有变量
    animal.set_weight(100)          # 设置私有变量
    print(animal.get_weight())    # 获取私有变量
    print(animal.__weight)        # 调用私有方法,会报错

 

2 测试结果

xiaobai
18
My name is xiaobai, I'm a tester, I'm 18 years old, my weight is 40
40
100
Traceback (most recent call last):
  File "F:/workspace/course_manager_perf/zdz_test/test_class.py", line 35, in <module>
    print(animal.__weight)        # 调用私有方法,会报错
AttributeError: 'Animal' object has no attribute '__weight'

 

posted @ 2021-02-08 21:07  栗子测试开发  阅读(89)  评论(0)    收藏  举报