Python面向对象基础

本文深入探讨了Python中类的创建与使用,包括类的属性、方法及内置类属性的展示。同时,通过实例演示了继承的概念,展示了子类如何调用父类的方法并覆盖父类的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. class


class Person:
    '人的基类'
    perCount=0

    def __init__(self, name, gender, age):
        self.name=name
        self.gender=gender
        self.age=age

        Person.perCount +=1

    def displayCount(self):
        print("Totoal Employee %d",Person.perCount)


    def displayEmployee(self):
        print("Name: ", self.name, ", age: ", self.age)

#Python内置类属性
print("Person.__doc__:" , Person.__doc__)#类的文档字符串
print("Person._name_:", Person.__name__)#类名
print("Person.__module__:",Person.__module__)#类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod)
print("Person.__bases__", Person.__bases__)#类的所有父类构成元素(包含了一个由所有父类组成的元组)
print("Person.__dict__:", Person.__dict__)# 类的属性(包含一个字典,由类的数据属性组成)

emp1=Person("Zara","female",18)
emp2=Person("Mi","male",18)

emp1.displayEmployee()

/Users/xxx/PycharmProjects/xxx/venv/bin/python /Users/xxx/PycharmProjects/xxx/ceshi.py
Person.__doc__: 人的基类
Person._name_: Person
Person.__module__: __main__
Person.__bases__ (<class 'object'>,)
Person.__dict__: {'__module__': '__main__', '__doc__': '人的基类', 'perCount': 0, '__init__': <function Person.__init__ at 0x108bcce18>, 'displayCount': <function Person.displayCount at 0x108bccd08>, 'displayEmployee': <function Person.displayEmployee at 0x108bccea0>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>}
Name:  Zara , age:  18

Process finished with exit code 0

self表示类的实例,非类本身。

2. inherit

class Person:
    '人的基类'
    def __init__(self, name, gender, age):
        self.name=name
        self.gender=gender
        self.age=age
    def modifyAttri(self,attri):
        self.attri=attri
        print("Attri: ",self.attri)

class Female(Person):
    '女性类'
    def __init__(self,hobby):
        self.hobby=hobby
        print("hobby: ",self.hobby)

    def getFamilyInfo(self):
        print("Ten members in hers family.")

c=Female("swimming")#实例化一个对象
c.getFamilyInfo()#调用子类方法
c.modifyAttri("SWIMING")#调用父类方法

hobby:  swimming
Ten members in hers family.
Attri:  SWIMING

Process finished with exit code 0

下面看下子类调用父类构造方法:

 

3. override

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值