温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Class与Object怎么在Python中使用

发布时间:2021-03-31 17:29:20 来源:亿速云 阅读:234 作者:Leah 栏目:开发技术

这期内容当中小编将会给大家带来有关Class与Object怎么在Python中使用,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

类和对象的概念很难去用简明的文字描述清楚。从知乎上面的一个回答中可以尝试去理解:

对象:对象是类的一个实例(对象不是找个女朋友),有状态和行为。例如,一条狗是一个对象,它的状态有:颜色、名字、品种;行为有:摇尾巴、叫、吃等。

类:类是一个模板,它描述一类对象的行为和状态。

class

class是用来定义类的。类在面向对象编程里面是很有用的,能够大大提升开发效率和代码维护性。直接上代码学习:

class student(object):
  def print_info(self):
    print("student's info is very important!")

student1 = student()
student1.print_info()

运行结果如图:

Class与Object怎么在Python中使用

class student():
  def __init__(self,name,gender):
    self.Name = name
    self.Gender = gender
    print("student's name is ",name,' and it is a ',gender)

testman = student("Mike","Male")

这个类可以通过一个__init__ 进行初始化,相当于定义类了。在主代码中,先要进行实例化,即testman = student() 然后才能调用里面的方法。运行结果如下:

Class与Object怎么在Python中使用

继承

关于继承,就是子类可以继承父类的公有函数。例如:

class Parent:
  def Family(self):
    print("we are family")

class Child(Parent):
  pass

father = Parent()
son = Child()

father.Family()
son.Family()

在这里,Parent 类是父类,Child 类是子类,但是通过定义,继承了父类。所以在后面实例化之后,son 依然可以调用父类的函数。最后的运行结果如下:

Class与Object怎么在Python中使用

override

当然,子类除了继承,还可以重写父类的函数功能。

class Parent:
  def Family(self):
    print("we are family")

class Child(Parent):
  def Family(self):
    print("hey,i am son")

father = Parent()
son = Child()

father.Family()
son.Family()

在这个例子中,Child 类重写了父类函数里面的Family 函数,最后的运行结果如下:

Class与Object怎么在Python中使用

super

super是一个超类。这个概念很抽象,但是用例子来说明一下就不会那么抽象了。

class Parent:
  def Family(self):
    print("we are family")

class Child(Parent):
  def Family(self):
    print("hey,i am son")
    super(Child,self).Family()
    print("again, i am son")

father = Parent()
son = Child()

father.Family()
son.Family()

运行结果如下:

从上面的例子很容易看出,super 就是将父类的函数再调用了一次。

Class与Object怎么在Python中使用

上述就是小编为大家分享的Class与Object怎么在Python中使用了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI