美文网首页
python 类和实例

python 类和实例

作者: 起名字真难难难 | 来源:发表于2022-04-26 14:44 被阅读0次
image.png
 class Student(object):
    # 在__init__方法中,将name、score变量属性直接绑定进来
    def __init__(self,name,score):
        self.name=name
        self.score=score
chloe=Student('Chloe',60)
print(chloe.name,chloe.score)   

运行结果:

image.png

数据封装&增加新方法

class Student(object):
    # 在__init__方法中,将name、score变量属性直接绑定进来
    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.score>90:
            return 'A'
        else:
            return 'B'
chloe = Student('Chloe', 60)
print(chloe.print_score())
print(chloe.get_grade())

访问权限

image.png

before

class Student(object):
    # 在__init__方法中,将name、score变量属性直接绑定进来
    def __init__(self,name,score):
        self.name=name
        self.score=score
    def print_score(self):
        print('%s:%s' %(self.name, self.score))
chloe=Student('Chloe',99)
print(chloe.name)
before

after

class Student(object):
  # 在__init__方法中,将name、score变量属性直接绑定进来
  def __init__(self,name,score):
      self.__name=name
      self.__score=score
  def print_score(self):
      print('%s:%s' %(self.__name, self.__score))
chloe=Student('Chloe',99)
print(chloe.__name)
变量被私有了 访问参数、更改参数
class Student1(object):
    def __init__(self,name,gender):
        self.name=name
        self.__gender=gender
    #     允许外部访问
    def get_gender(self):
        return self.__gender
    # 允许外部更改
    def set_gender(self,gender):
        self.__gender=gender
bart=Student1('songjiang','female')
bart=Student1('SJ','male')
print(bart.name,bart.get_gender())
image.png

相关文章

  • Python实例变量和类变量

    Python实例变量和类变量 类变量(类属性): 类变量属于类所有,所有实例共享一个变量 实例变量(实例属性) 实...

  • Python 类和类实例

  • 1.14类代码编写基础

    一、类对象和实例对象 在python对象模型中,类和通过类产生的实例是两种不同的对象类型: 类类是实例工厂。类的属...

  • python类的实例方法、静态方法和类方法区别及其应用场景

    python类的实例方法、静态方法和类方法区别及其应用场景 一、先看语法,python类语法中有三种方法,实例方法...

  • python类的实例方法、静态方法和类方法区别及其应用场景

    python类的实例方法、静态方法和类方法区别及其应用场景 一、先看语法,python 类语法中有三种方法,实例方...

  • python 类和实例

    面向对象最重要的概念就是类(Class)和实例(Instance),必须牢记类是抽象的模板,比如Student类,...

  • Python 类和实例

    类是创建实例的模板,而实例则是一个一个具体的对象,各个实例拥有的数据都互相独立,互不影响 廖雪峰博客:http:/...

  • python类和实例

    类 类是一种数据结构,可用于创建实例。(一般情况下,类封装了数据和可用于该数据的方法) Python类是可调用的对...

  • Python类和实例

    关键词:class 继承和多态:(object) 如果没有其他需要继承的类,则默认继承(object) 多态这里和...

  • Python类和实例

    @[toc] 1.类和实例 面向对象最重要的概念就是类(Class)和实例(Instance),必须牢记类是抽象的...

网友评论

      本文标题:python 类和实例

      本文链接:https://www.haomeiwen.com/subject/jofyaltx.html