类的成员 练习

  1. 面向对象的私有成员有什么?

    1.私有类的静态属性
    2.私有对象属性
    3.私有类的方法
  2. 如何设置面向对象的类方法与静态方法,类方法静态方法有什么用?

    1.类方法:@classmethod  得到类名可以实例化一个对象,可以操作类的属性
    2.静态方法:@staticmethod保持代码的一致性,提高代码的维护性
  3. 面向对象中属性是什么?有什么作用?

    1.@property将动态方法伪装成属性,看起来更加合理
  4. isinstance与issubclass的作用是什么?

    1.isinstance(a,b)判断a是否是b类的或b类派生类的对象
    2.issubclass(a,b)判断a类是否是b类或b类派生类的子类
  5. 看代码写结果:

    class A:
        a = 1
        b = 2
        def __init__(self):
            c = 3
    
    obj1 = A()
    obj2 = A()
    obj1.a = 3
    obj2.b = obj2.b + 3
    print(A.a)
    print(obj1.b)
    print(obj2.c)
    
    结果
    1
    2
    报错
  6. 看代码写结果:

    class Person:
        name = 'aaa'
    
    p1 = Person()
    p2 = Person()
    p1.name = 'bbb'
    print(p1.name)
    print(p2.name)
    print(Person.name)
    bbb
    aaa
    aaa
  7. 看代码写结果:

    class Person:
        name = []
    
    p1 = Person()
    p2 = Person()
    p1.name.append(1)
    print(p1.name)
    print(p2.name)
    print(Person.name)
    [1]
    [1]
    [1]
  8. 看代码写结果:

    class A:
    
        def __init__(self):
            self.__func()
    
        def __func(self):
            print('in A __func')
    
    
    class B(A):
    
        def __func(self):
            print('in B __func')
    
    
    obj = B()
    in A __func
  9. 看代码写结果:

    class Init(object):
    
        def __init__(self,value):
            self.val = value
    
    class Add2(Init):
    
        def __init__(self,val):
            super(Add2,self).__init__(val)
            self.val += 2
    
    class Mul5(Init):
    
        def __init__(self,val):
            super(Mul5, self).__init__(val)
            self.val *= 5
    
    class Pro(Mul5,Add2):
        pass
    
    class Iner(Pro):
        csup = super(Pro)
        def __init__(self,val):
            self.csup.__init__(val)  
            self.val += 1
    # 虽然没有见过这样的写法,其实本质是一样的,可以按照你的猜想来。
    p = Iner(5)
    print(p.val)
    36
  10. 请按下列要求,完成一个商品类。

    • 封装商品名,商品原价,以及折扣价。
    • 实现一个获取商品实际价格的方法price。
    • 接下来完成三个方法,利用属性组合完成下列需求:
      • 利用属性property将此price方法伪装成属性。
      • 利用setter装饰器装饰并实现修改商品原价。
      • 利用deltter装饰器装饰并真正删除原价属性。
    class Goods:
        def __init__(self,name,original_price,discount):
            self.name = name
            self.original_price = original_price
            self.discount =discount
        @property
        def price(self):
            return self.original_price * self.discount
        @price.setter
        def price(self,value):
            self.original_price = value
        @price.deleter
        def price(self):
            del self.original_price
    DY = Goods("大衣",100,0.95)
    print(DY.price)
    DY.price = 1000
    print(DY.price)
    del DY.price
    print(DY.__dict__)
    

猜你喜欢

转载自www.cnblogs.com/ciquankun/p/11324392.html