本文实例讲述了Python面向对象之类的定义与继承用法。分享给大家供大家参考,具体如下:
定义一个类
类中的方法同,类外方法,默认传self
值
类的构造函数是 __init__
1
2
3
4
5
6
7
8
|
# -*- coding:utf-8 -*-
class Hello:
def __init__( self ,name):
self .name = name
def sayHello( self ):
print ( "Hello Python {0}" . format ( self .name))
h = Hello( "Newer" )
h.sayHello()
|
运行结果:
Hello Python Newer
继承
例子:注意父类构造函数和继承格式的书写
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# -*- coding:utf-8 -*-
class Hello:
def __init__( self ,name):
self .name = name
def sayHello( self ):
print ( "Hello Python {0}" . format ( self .name))
class Hi(Hello):
def __init__( self ,name):
Hello.__init__( self ,name)
def sayHi( self ):
print ( "Hi {0}" . format ( self .name))
h1 = Hi( "Newer" )
h1.sayHi()
|
运行结果:
Hi Newer
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/YANG_Gang2017/article/details/78150573