Python类和实例

2019-05-12

类和实例

1.类和实例

实例是根据类创建出来的一个个具体的“对象”,每个对象由拥有相同的方法。</br>

class Student(object):
  
  def _init_(self,name,score):   #通过_init_方法,把一些认为必须绑定的属性填写进去
    self.name=name
    self.score=score

>>>bart=student(‘BestinLi’,59)     #所以创建实例的时候不能传递空参数,self属性表示创建的实例本身,不用传

<font color='maroon'>类当中定义的函数与普通函数的区别在于,第一个参数永远是实例变量self,并且调用时,不用传递该参数。</font>

2.数据封装(即对类添加一些方法,可以从类的内部访问实例的数据)

class Student(object):
  def _init_(self,name,score):
    self.name=name
    self.score=score

  def print_score(self):
    print('%s','%s' %(self.name,self.score))

  def get_grade(self):
    if self.code>=90:
      return 'A'
    elif self.score >=60
      return 'B'
    else:
      return 'C'

  >>>bart=student('Bestin',59)
  >>>message=bart.print_score()
  >>>resule=bart.get_grade()

<font color='maroon'>要让内部属性不被外部访问,可以把属性的名称前加上两个下划线__,使该属性变为私有变量,只有内部可以访问,外部不可以!!!</font>

def Studeng(object):
  def _init_(self,name,score)
    self.__name=name
    self.__score=score

  def print_score(self):
    print('%s','%s' $(self.name,self.score))

  def get_name(self):
    return self.__name

  def get_score(self):
    return self.__score

  def set_score(self,score):
    if 0<=score<=100:
      self._score=score
    else:
      raise ValueError('bad score')

>>>bart=Studeng('Bestin',59)
>bart.__name   #无法获得此数据
>>>bart.get_name()   #可以获得数据
>>>bart.set_score(80)  #修改私有变量数据

下面为一个典型的错误写法
bart.__name='Bestin Li' 
表面上看,外部代码“成功”地设置了__name变量,但实际上这个__name变量和class内部的__name变量不是一个变量!内部的__name变量已经被Python解释器自动改成了_Student__name,而外部代码给bart新增了一个__name变量。

3.继承和多态

在面向对象(OOP)的程序设计中,当我们定义一个class的时候,可以从某个现有的class继承,新的class称为子类,而被继承的class称为基类,父类或者超类。</br>
<font color='maroon'>继承最大的好处就是子类获得了父类的全部功能。</font></br>
<font color='maroon'>当我们定义一个class的时候,我们实际上就定义了一种数据类型,这种自定义的数据类型和python自带的数据类型,如list,dict没什么区别。即Bart的数据类型就是Student。</font>

class Animal(object):

  def _init_(self):
    pass

  def run(self):
     print('Animal is Running!!!' )

class Dog(Animal):

  def _init_(self):
    pass

  def run(self):
    print('Dog is Running!!!')

class Cat(Animal):

  def _init_(self):
    pass

  def run(self):
    print('Cat is running!!!')

def run_twice(animal):
  animal.run()
  animal.run()

>>>Animal=Animal()
>>>Animal.run()
>>>Dog=Dog()
>>>Dog.run()
>>>Cat=Cat()
>>>Cat.run()

>>>run_twice(Dog())
>Dog is running!!!
>Dog is running!!!

<font color='maroon'>任何依赖Animal作为参数的函数或者方法都可以不加修改地正常运行,原因就在于多态</font>

4.获取对象信息

>>>type(123)
><class 'int'>
>>>type('str')
><class 'str'>
>>>type(Dog)
><class '_main_.Animal'>

>>>isinstance(Dog,Animal)  #总是优先使用isinstance()判断类型,可以将指定类型及其子类“一网打尽”
>true
>>>isinstance(Husky,(Animal,Dog,Cat))
>true

>>>dir(Dog)  #dir()获得一个对象的所有属性和方法,他返回一个字符串list
>[Dog所有的属性和方法]

class MyObject(object):

  def _init_(self):
    self.x=9

  def power(self):
    return self.x*self.x

>>>hasattr(obj,'x') #有属性(方法)x吗?
>true
>>>setattr(obj,'y',19) #设置一个属性y
>>>hasattr(obj,'y')
>true
>>>getattr(obj,'y') #获取属性(方法)y
>19
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容