Python面向对象

参考https://www.liaoxuefeng.com/wiki/1016959663602400/1017495723838528

面向对象编程——Object Oriented Programming,简称OOP,是一种程序设计思想。OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的函数。

 

创建类

class Animal:

#__init__ 类的构造方法,在类实例化时执行

  def __init__(self,name,age) #self指实例变量本身,实例化时不需要对self进行赋值,Python解释权将自动把实例变量传入self

    self.name = name

    self.age = age

  def sit(self): #类的方法

    print(self.name + " is now sitting")

 

实例化(创建对象)

dog = Animal('xiaohua',2) #创建实例通过类名()实现

print(dog.name)  output:xiaohua #实例变量

dog.sit() output:xiaohua is now sitting #实例方法

 

访问限制

Python中允许类外部修改实例变量的值

class Car():
    def __init__(self,make,model,year,odometer_reading):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = odometer_reading #属性的默认值
        
    def get_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name
    
    def get_odometer_reading(self):
        print("This car has " + str(self.odometer_reading) + 'miles on it')
        
my_car = Car('audi','a4','2018',200)
my_car.odometer_reading = 300  ##直接在类外部访问属性 并且修改属性值
print(my_car.get_name())
my_car.get_odometer_reading()

 如果要让内部属性不被外部访问,可以把属性的名称前加上两个下划线__

class Car():
def __init__(self,make,model,year,odometer_reading):
self.make = make
self.model = model
self.year = year
self.__odometer_reading = odometer_reading #属性的默认值

def get_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name

def get_odometer_reading(self):
print("This car has " + str(self.odometer_reading) + 'miles on it')

my_car = Car('audi','a4','2018',200)
print(my_car.__odometer_reading)



output:AttributeError: 'Car' object has no attribute '__odometer_reading'

 

继承

class Animal:

  def __init__(self,name,age) 

    self.name = name

    self.age = age

  def sit(self): 

    print(self.name + " is now sitting")



class Dog(Animal): #继承Animal类,获得了父类的属性和方法

  def run(self):

    print(self.name + "is now running")

  def sit(self):#重写父类方法

    print(self.name + "is now sitting.my age is" + str(self.age) )

dog  = Dog("xiaohua",3)

dog.sit() #xiaohua is now sitting.my age is 3。

 

2020-03-18 17:02

 

posted @ 2020-03-18 17:03  傅余生  阅读(137)  评论(0编辑  收藏  举报