Python面向对象编程

Python包与模块管理,面向对象编程

在这里插入图片描述

在这里插入图片描述

# 创建一个学生类
class Student:
    
    # 定义学生属性,初始化方法
    def __init__(self, name, score):
        self.name = name
        self.score = score

    # 定义打印学生信息的方法
    def show(self):
        print("Name: {}. Score: {}".format(self.name, self.score))
# 实例化
student1 = Student("John", 100)
student2 = Student("Lucy", 99)

Student是类,student1和student2是我们创建的具体的学生对象。当我们输入上述代码时,Python会自动调用默认的__init__初始构造函数来生成具体的对象。关键字self是个非常重要的参数,代表创建的对象本身。

__repr__函数就是在打印类的时候,控制类输出的字符串。
在这里插入图片描述

class Item:
    def __init__(self,name):
        self.name = name
    def __repr__(self):
        return 'Iiitem({!r})'.format(self.name)
print(Item('aaaaa'))

类变量和实例变量

# 创建一个学生类
class Student:

# number属于类变量,定义在方法外,不属于具体实例
    number = 0

 def __init__(self, name, score):
    self.name = name
    self.score = score
    Student.number = Student.number + 1

  # 定义打印学生信息的方法
 def show(self):
    print("Name: {}. Score: {}".format(self.name, self.score))
   #类方法#
  def total():
        print('total:{}'.format(Student.number))


   s=Student('asd',90)
   print(Student.number)
   s2=Student('asdd',99)
   print(Student.number)
   s3=Student('dd',88)
   print(s3.number)
   print(Student.number)
   Student.total()
   >1
   >2
   >3
   >3
   >total:3
类变量:类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。访问或调用类变量的正确方式是类名.变量名。
实例变量:定义在方法中的变量,属于某个具体的对象。访问或调用实例变量的正确方式是对象名.变量名

继承

#创建父类#
class Schoolmember:
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def tell(self):
        print('name:{} , age:{}'.format(self.name,self.age))

#创建子类#
class Teacher(Schoolmember):
    def __init__(self,name,age,salary):
        Schoolmember.__init__(self,name,age)
        self.salary = salary
    #方法重写#
    def tell(self):
        Schoolmember.tell(self)
        print('salary:{}'.format(self.salary))

class Student(Schoolmember):
    def __init__(self,name,age,score):
        Schoolmember.__init__(self,name,age)
        self.score = score

    def tell(self):
        Schoolmember.tell(self)
        print('score:{}'.format(self.score))

 teacher = Teacher('John',30,8000)
 student = Student('Lee',12,90)
  
 teacher.tell()
 student.tell()
> name:John , age:30
>salary:8000
>name:Lee , age:12
>score:90

​​​​

属性

​​在这里插入图片描述

@property 定义属性
属性的本质是函数,只是在调用的时后不用像函数那样,只需要.就行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值