栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

十七. python面向对象

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

十七. python面向对象

17.1 创建类对象
#!/usr/bin/python3
class Dog:
    name = "haha"
    def eat(self):
        return "eat food"
# 实例化类
x = Dog()
# 访问类的属性和方法
print("Dog 类的属性 name 为:", x.name)
print("Dog 类的方法 eat 输出为:", x.eat())

结果:

Dog 类的属性 name 为: haha
Dog 类的方法 eat 输出为: eat food

17.2 构造函数
#!usr/bin/python3
class Dog:
    name = "haha10"
    def __init__(self,name):
        self.name = name

x = Dog("12345")
print("name = ", x.name)

结果:

name = 12345

17.3 私有属性

访问私有属性会报错

#!/usr/bin/python3
class people:
    # 定义私有属性,私有属性在类外部无法直接进行访问
    __name = "zhangsan"

# 实例化类
p = people()
print("name = ", p.__name)#这里会报错

结果:

Traceback (most recent call last):
  File "/Users/bytedance/source/builder/builder/handler/test.py", line 10, in
    print("name = ", p.__name)
AttributeError: 'people' object has no attribute '__name'

17.4 私有方法

与私有属性一样,私有方法也不能在外部访问,定义私有方法也是在方法名前面加__,在外部调用私有方法会报错

#!usr/bin/python3
class student():
    def __get_name(self):
        print("student")

x = student()
x.__get_name() #这行会报错

结果:

Traceback (most recent call last):
  File "/Users/bytedance/source/builder/builder/handler/test.py", line 7, in
    x.__get_name() #这行会报错
AttributeError: 'student' object has no attribute '__get_name'

17.5 继承

与java一样,Python 同样支持类的继承

#!/usr/bin/python3
class people:
    def get_name(self):
        print("我叫张三")

class student(people):
    pass

s = student()
s.get_name()

结果:

我叫张三

17.6 方法重写
#!usr/bin/python3
class people:
    def get_name(self):
        print("wo shi zhangsan10")

class student(people):
    def get_name(self):
        print("hahahaha")

x = student()
x.get_name()

结果:

hahahaha

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/738655.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号