Python面向对象编程

类和实例(类是抽象的模板,实例是根据类创建出来的对象)

class Student(object):   # 定义类  ()内的元素表示当前定义的类是从哪里继承的
    def __init__(self,name,score): #绑定属性__init__  (相当于其他语言的constructor)
        self.name = name
        self.score = score
    def print_score(self):  #绑定方法
        print("%s:%s" % (self.name,self.score))

bat = Student("fred",98) #创建实例
bat.name = "vip"   #可自由的给实例变量绑定属性
bat.print_score()   #vip:98
访问限制(使用私有作用域,只能在内部访问。实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问)
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_name(self): #读取内部属性
        return self.__name
    def set_name(self,newName): #设置内部属性
        self.__name = newName
classmate = Student("fred",98)
print(classmate.__name) #'Student' object has no attribute '__name'
继承和多态
  • 继承:被继承的称谓基类、父类或超类,继承的称为子类。子类获得父类的全部功能
  • 多态:当父类和子类都存在同一个属性或方法时,在调用时总是调用子类的属性或方法
class Animal(object):
    def run(self):
        print("animal is run")
class Cat(Animal):  #Cat继承Animal
    def run(self):
        print("Cat is run")
cat = Cat()
cat.run()   #Cat is run (多态)
isinstance(cat,Animal)  #True 判断cat是否是Animal类型
获取对象信息
  • 判断类型 type() isinstance()
type(123)
isinstance([],list) #优先使用isinstance()
  • 获取对象的属性和方法 dir() 返回一个包含字符串的list
dir('ABC')   #['__add__', '__class__',...,'zfill']
  • 直接操作对象的状态:getattr()、setattr()、hasattr()
class Test(object):
    def __init__(self,name):
        self.name = name
    def say_name(self):
        print(self.name)
test = Test("fred")
hasattr(test,"name") #True  
getattr(test,"say_name")    #<bound method Test.say_name of <__main__.Test object at 0x0000000005DA6198>>
实例属性和类属性
class Student(object):
    name = "fred"
s = Student()
print(s.name)   #fred   读取类属性
s.name = "vip"
print(s.name)   #vip    读取实例属性
原文地址:https://www.cnblogs.com/sghy/p/8080085.html