1.实例属性与类属性
与Java语言的静态属性和成员属性类似,在python中通过self绑定的属性称为实例属性,在类中直接定义的属性称为类属性。
类属性通过实例也可以访问和修改,但是更推荐使用类名去访问和修改。
实例:
# -*- coding: utf-8 -*-
# @Time : 2022/4/7 16:23
# @File : objectinfo.py
# @Software : PyCharm
class Animal(object):
pass
class Human(Animal):
# 类属性
earth = '地球'
# 构造方法
def __init__(self, name, gender, age):
self.name = name
self.gender = gender
# 私有属性age
self.__age = age
def eat(self):
print(self.name, " is eating....")
h1 = Human('张三', '男', 20)
h2 = Human('李四', '女', 18)
print(h1.earth)
print(h2.earth)
print(h1.earth == h2.earth)
print(Human.earth)
Human.earth = '火星'
print(Human.earth)
运行结果:
地球
地球
True
地球
火星