zoukankan      html  css  js  c++  java
  • python练习2

    #由于Python是动态语言,根据类创建的实例可以任意绑定属性。
    #给实例绑定属性的方法是通过实例变量,或者通过self变量:
    #这一点不同于静态语言
    class Student(object):
        def __init__(self, name, gender):
            self.name = name
            self.age = 21
            self.__gender = gender
    
    
        def get_gender(self):
            return self.__gender
    
    
        def set_gender(self,gender):
            if gender not in ['male','female']:
                raise ValueError('bad gender')
            self.__gender=gender
    
    
        def get_age(self):
            return self.age
    
    
    # 测试:
    bart = Student('Bart', 'male')
    bart.grade = 100
    if bart.get_gender() != 'male':
        print('测试失败!')
    else:
        bart.set_gender('female')
        if bart.get_gender() != 'female':
            print('测试失败!')
        else:
            print('测试成功!')
    
    
    L = dir(bart)
    cnt = 0
    for item in L:
        print(item,end='  ')
        cnt+=1
        if cnt % 3 ==0:
            print('')
    
    
    print(bart.grade)
    #类属性是类所有的,实例属性是类对应实例属性所有的
    class Student(object):
        count = 0
    
    
        def __init__(self, name):
            self.name = name
            Student.count+=1
    
    # 测试:
    if Student.count != 0:
        print('测试失败!')
    else:
        bart = Student('Bart')
        if Student.count != 1:
            print('测试失败!')
        else:
            lisa = Student('Bart')
            if Student.count != 2:
                print('测试失败!')
            else:
                print('Students:', Student.count)
                print('测试通过!')
    
    class Screen(object):
        @property
        def width(self):
            return self._width
    
    
        @property
        def height(self):
            return self._height
    
    
        @width.setter
        def width(self,width):
            self._width = width
    
    
        @height.setter
        def height(self,height):
            self._height = height
    
    
        @property
        def resolution(self):
            return self._height * self._width
    
    
    # 测试:
    s = Screen()
    s.width = 1024
    s.height = 768
    print('resolution =', s.resolution)
    if s.resolution == 786432:
        print('测试通过!')
    else:
        print('测试失败!')

  • 相关阅读:
    hdu-1698(线段树,区间修改)
    hdu-1394(线段树)
    hdu-1166(线段树)
    hdu-1251(string+map)
    hdu-1711(kmp算法)
    hdu-2191(完全背包+二进制优化模板)
    hdu-2844(完全背包+二进制优化模板)
    hdu-1171(多重背包+二进制优化)
    SpringMVC 参数中接收数组、List写法
    如何高效的查询数组中是否包含某个值
  • 原文地址:https://www.cnblogs.com/MalcolmMeng/p/8442962.html
Copyright © 2011-2022 走看看