• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python实例化对象的具体方法

python 搞代码 4年前 (2022-01-09) 18次浏览 已收录 0个评论

python中同样使用关键字class创建一个类,类名称第一个字母大写,可以带括号也可以不带括号;python中实例化类不需要使用关键字new(也没有这个关键字),类的实例化类似函数调用方式;

# coding: utf-8
# 创建一个类,类名称第一个字母大写,可以带括号也可以不带括号
 
class Student(): 
    student_count = 0 
    def __init__(self, name, salary):
        self.name = name
        self.age = salary
        Student.student_count += 1 
    def display_count(self):
        print('Total student {}'.format(Student.student_count)) 
    def display_student(self):
        print('Name: {}, age: {}'.format(self.name,self.age)) 
    def get_class(self):
        if self.age >= 7 and self.age < 8:
            return 1
        if self.age >= 8 and self.age < 9:
            return 2
        if self.age >= 9 and self.age < 10:
            return 3
        if self.age >= 10 and self.age < 11:
            return 4
        else:
            return  0

创建类的对象(实例化类)

python中实例化类不需要使用关键字new(也没有这个关键字),类的实例化类似函数调用方式。

student1 = Student('cuiyongyuan',10)
student2 = Student('yuanli', 10)
 
student1.display_student()
student2.display_student()
 
student1_class = student1.get_class()
student2_class = student2.get_class()

实例扩展:

实例化过程:

class luffy_stu:
  def __init__(self,name,age,sex):
    self.name = name
    self.age = age
    self<b style="color:transparent">本文来源gao@!dai!ma.com搞$$代^@码网*</b>.sex = sex
  def eat(self):
    pass
if __name__=="__main__":
  stu1 = luffy_stu('bao',21,'male')
  #实例化过程:
  #1. 是先产生一个stu1对象,
  #2. luffy_stu.__init__('stu1','bao',21,'male')再将stu1对象传入__init__构造函数中实例化对象

以上就是python实例化对象的具体方法的详细内容,更多关于python如何实例化对象的资料请关注搞代码其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python实例化对象的具体方法
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址