私有 __方法,__属性
类的属性和方法,可以通过对象进行访问
子类继承父类,继承了父类的公有方法、属性
dir(对象名):显示对象的属性和方法
继承也能查看私有的属性和方法
直接访问
间接访问:给出一个共有方法
强类型
弱类型
多态:提高有参数函数、方法的复用性
类属性:(修改多个对象的某个特征更加简单,程序运行中)
# 1/类名.类属性名
print(person.contry)
yang = person('yang')
print(yang.country)
# 2 类属性的重新赋值(唯一一种方式)
person.country = 'ruby'
yang = person('yang')
# 给实类对象添加了一个和类属性同名的实类属性
yang.country = 'henan'
print(person.country)
print(yang.country)
多态:不同的对象做相同的操作有不同的结果
# 修饰器
# cls -> class -> Person
@classmethod
def get_country(cls):
return cls.__country
# 类方法调用
# 类方法(class,)类方法配合调用私有类属性
person.get_country()
person().get_country()
@staticmethod
def hello():
print('hello')
# init
# 监听对象创建成功后,给对象添加属性并赋值
# 追踪通过这个类创建的对象的属性值变化的
# 监听内存地址的引用计数位0,(监听对象销毁)
# __new__
# 监听对象创建成功并返回对象
def __new__(cls, *args, **kwargs):
return object.__new__(cls)
# 单例设计模式:通过一个类创建出来的所有的对象的地址都是一样的
# 如果想使用这个类创建的对象代表不同的事物,正常创建即可
# 如果只是想使用类中的方法,不关心对象是不同的对象,可以使用单例模式,(节约内存)
# new
# 空值类型
n = None
type = NoneType
id(n)# python已经开辟好的空间保存当前的空值类型
None == False
例子1:
class Person(object):
# __country 类变量:可以通过类名、或者对象直接调用
__country = 'china'
# 定义一个类属性保存对象
instance = None
def __new__(cls, *args, **kwargs):
# 判断是否第一次创建对象
if not cls.instance:
cls.instance = object.__new__(cls)
return cls.instance
def __init__(self):
self.__name = 'yang'
@classmethod
def get_country(cls):
return cls.__country
def func(self):
print(self.__name)
@staticmethod
def hello():
print('hello')
print(id(Person()))
print(id(Person()))
print(Person().get_country())
print(Person().func())# 函数执行完事之后,打印的话为None
例子2:
class person(object):
def __init__(self, name, age, money):
self.name = name
self.age = age
self.__money = money
def __step(self):
print(self)
class women(person):
pass
yang = women('yue', 18, 1000)
print(dir(yang))
# 可以访问继承的类的私有属性
print(yang._person__money)
print(yang._person__step)