类与对象

类与对象

对象=属性+方法

对象是类的实例。换句话说,类主要定义对象的结构,然后我们以类为模板创建对象。类不但包含方法定义,而且还包含所有实例共享的数据。

  • 封装:信息隐蔽技术

用关键字class定义python类,关键字后面紧跟类的名称分号类的实现
<注>:python中类的名字约定以大写字母开头
Python类也是对象。它们是type的实例

class Amen:
#属性
    banji=4
    nianji=9
    sex='boy'
    chengji='good'
#方法
    def word(self):
        print("i'm trying to make progress.")
    def eat(self):
        print("i'm eating healthy every day.")
    def exercise(self):
        print("i exercise every day.")
    def sleep(self):
        print("i have enough sleep.")

colaj=Amen()
print(colaj)
print(type(colaj))
print(colaj.__class__)
print(colaj.__class__.__name__)
colaj.sleep()
print(colaj.sex)
#<__main__.Amen object at 0x00000203B420F370>
#<class '__main__.Amen'>
#<class '__main__.Amen'>
#Amen
#i have enough sleep.
#boy
  • 继承:子类自动共享父类之间数据和方法的机制
class MyList(list):
    pass


lst = MyList([1, 5, 2, 7, 8])
lst.append(9)
lst.sort()
print(lst)

# [1, 2, 5, 7, 8, 9]
  • 多态:不同对象对同一方法响应不同的行动
class Men:
    def age(self):
        pass
class Child(Men):
    def age(self):
        print("between 1 and 12 years old")
class Teenager(Men):
    def age(self):
        print("between 13 and 19 years old")
def myfun(Men):
    Men.age()
myfun(Child())#between 1 and 12 years old
myfun(Teenager())#between 13 and 19 years old

self

Python 的 self 相当于 C++ 的 this 指针。

class Test:
    def prt(self):
        print(self)
        print(self.__class__)


t = Test()
t.prt()
# <__main__.Test object at 0x000000BC5A351208>
# <class '__main__.Test'>

类的方法与普通的函数只有一个特别的区别 —— 它们必须有一个额外的第一个参数名称(对应于该实例,即该对象本身),按照惯例它的名称是 self。在调用方法时,我们无需明确提供与参数 self 相对应的参数。

class Men:
    def setname(self,name):
        self.name=name
    def speak(self):
        print("my name is %s."%self.name)
a=Men()
a.setname("colaj")
a.speak()#my name is colaj.
b=Men()
b.setname("keke")
b.speak()#my name is keke.

Python 的魔法方法

python中可以给你的类增加魔力的特殊方法…

如果你的对象实现了这些方法中的某一个,那么这个方法就会在特殊的情况下被 Python 所调用,而这一切都是自动发生的…

类有一个名为__init__(self[, param1, param2…])的魔法方法,该方法在类实例化时会自动调用。

class Men:
    def __init__(self,name):
        self.name=name
    def speak(self):
        print("my name is %s."%self.name)
a=Men("colaj")
a.speak()#my name is colaj.
b=Men("keke")
b.speak()#my name is keke.

公有和私有

在 Python 中定义私有变量只需要在变量名或函数名前加上“__”两个下划线,那么这个函数或变量就会为私有的了。
例:私有属性

class Jisuan:
    __secretcount=0 释:私有变量
    publiccount=0 释:公共变量
    def count(self):
        self.__secretcount+=2
        self.publiccount+=1
        print(self.__secretcount)

a=Jisuan()
a.count()#2
a.count()#4
print(a.publiccount)#2
print(a.__secretcountS)#AttributeError: 'Jisuan' object has no attribute '__secretcountS'

例:类的私有方法

class Men:
    def __init__(self,name,grade):
        self.name=name
        self.grade=grade
    def introduction(self):
        print("name:{0},grade:{1}".format(self.name,self.grade))
    def __siyou(self):
        print("this is a privately way")
    def gongkai(self):
        print("this is a public way")
        self.__siyou()
        
a=Men("colaj",9)
a.introduction()#name:colaj,grade:9
a.gongkai()
#this is a public way
#this is a privately way
a.__siyou()
#AttributeError: 'Men' object has no attribute '__siyou'        

继承

Python 同样支持类的继承,派生类的定义如下所示:
在这里插入图片描述
BaseClassName(示例中的基类名)必须与派生类定义在一个作用域内。除了类,还可以用表达式,基类定义在另一个模块中时这一点非常有用:
在这里插入图片描述
例:如果子类中定义与父类同名的方法或属性,则会自动覆盖父类对应的方法或属性。

class Dog: 
    name=""
    age=0
    __sex=""
    def __init__(self,n,a,s):
        self.name=n
        self.age=a
        self.__sex=s
    def introduction(self):
        print("my name is {0},i'm {1} years old.".format(self.name,self.age))

class golden_retriever(Dog):
    weight=0
    def __init__(self,n,a,s,w):
        Dog.__init__(self,n,a,s)
        self.weight=w
    def introduction(self):
        print("my name is {0},i'm {1} years old,my weight is {2} kilgrams".format(self.name,self.age,self.weight))
a=golden_retriever("keke",4,"girl",40)
a.introduction()
#my name is keke,i'm 4 years old,my weight is 40 kilgrams

如果上面的程序去掉:Dog.init(self,n,a,s),则输出: my name is ,i’m 0 years old, my weight is 40 kilgrams.因为子类的构造方法把父类的构造方法覆盖了。
例:

import random
class People:
    def __init__(self):
        self.x=random.randint(0,20)
        self.y=random.randint(0,20)
    def move(self):
        self.x-=2
        self.y+=3
        print("my location:",self.x,self.y)
class Pupil(People):
    pass
class Middle_school_students(People):
    pass
class Undergraduate(People):
    def __init__(self):
        self.duty=True
    def work(self):
        if self.duty:
            print("we have great responsibilities and we must work hard. ")
            self.duty=False
        else:
            print("i'm tired,i want to have a rest.")
            self.duty=Ture

a=Pupil()
a.move()#my location: 10 11
a.move()#my location: 8 14
b=Undergraduate()
b.work()#we have great responsibilities and we must work hard. 
b.work()#i'm tired,i want to have a rest.
b.move()#AttributeError: 'Undergraduate' object has no attribute 'x'

解决该问题可用以下两种方式:
1.调用未绑定的父类方法Fish.init(self)

import random
class People:
    def __init__(self):
        self.x=random.randint(0,20)
        self.y=random.randint(0,20)
    def move(self):
        self.x-=2
        self.y+=3
        print("my location:",self.x,self.y)
class Pupil(People):
    pass
class Middle_school_students(People):
    pass
class Undergraduate(People):
    def __init__(self):
        People.__init__(self)
        self.duty=True
    def work(self):
        if self.duty:
            print("we have great responsibilities and we must work hard. ")
            self.duty=False
        else:
            print("i'm tired,i want to have a rest.")
            self.duty=True

a=Pupil()
a.move()#my location: 10 14
a.move()#my location: 8 17
b=Undergraduate()
b.work()#we have great responsibilities and we must work hard. 
b.work()#i'm tired,i want to have a rest.
b.move()#my location: 11 18

2.使用super函数super().init()

import random
class People:
    def __init__(self):
        self.x=random.randint(0,20)
        self.y=random.randint(0,20)
    def move(self):
        self.x-=2
        self.y+=3
        print("my location:",self.x,self.y)
class Pupil(People):
    pass
class Middle_school_students(People):
    pass
class Undergraduate(People):
    def __init__(self):
        super().__init__()
        self.duty=True
    def work(self):
        if self.duty:
            print("we have great responsibilities and we must work hard. ")
            self.duty=False
        else:
            print("i'm tired,i want to have a rest.")
            self.duty=True

a=Pupil()
a.move()#my location: 12 11
a.move()#my location: 10 14
b=Undergraduate()
b.work()#we have great responsibilities and we must work hard.
b.work()#i'm tired,i want to have a rest.
b.move()#my location: 12 12

**Python 虽然支持多继承的形式,但我们一般不使用多继承,因为容易引起混乱。
**
在这里插入图片描述
<注>:需要注意圆括号中父类的顺序,若是父类中有相同的方法名,而在子类使用时未指定,Python 从左至右搜索,即方法在子类中未找到时,从左到右查找父类中是否包含方法。
例:

class Dog:
    name=""
    sge=""
    __sex=""
    def __init__(self,n,a,s):
        self.name=n
        self.age=a
        self.sex=s
    def speak(self):
        print("my name is {0},i'm {1} years old.".format(self.name,self.age))
class Godlen_retriever(Dog):
    weight=0
    def __init__(self,n,a,s,w):
        Dog.__init__(self,n,a,s)
        self.weight=w
    def speak(self):
        print("my name is {0},i'm {1} years old.my weight is {2} kilgrams".format(self.name,self.age,self.weight))

class Speaker:
    topic = ''
    name = ''

    def __init__(self, n, t):
        self.name = n
        self.topic = t

    def speak(self):
        print("my name is {0},my topic is {1}" .format(self.name, self.topic))


class Sample01(Speaker,Godlen_retriever):
    a=""
    def __init__(self, n, a, s,w, t):
        Godlen_retriever.__init__(self, n, a, s, w)
        Speaker.__init__(self, n, t)
        # 方法名同,默认调用的是在括号中排前地父类的方法
test = Sample01("Tim", 25, 80, 4, "Python")
test.speak()#my name is Tim,my topic is Python


class Sample02(Godlen_retriever, Speaker):
    a = ''

    def __init__(self, n, a, w, g, t):
        Godlen_retriever.__init__(self, n, a, w, g)
        Speaker.__init__(self, n, t)
        # 方法名同,默认调用的是在括号中排前地父类的方法
test = Sample02("Tim",  5, 80, 4, "Python")
test.speak() #my name is Tim,i'm 5 years old.my weight is 4 kilgrams

组合

例:

class Boy:
    def __init__(self,x):
        self.num=x
class Girl:
    def __init__(self,x):
        self.num=x
class banji:
    def __init__(self,a,b):
        self.boy=Boy(a)
        self.girl=Girl(b)
    def prt(self):
        print("this banji have {0} boys and {1} girls.".format(self.boy.num,self.girl.num))

B=banji(3,4)
B.prt()
#class Boy:
    def __init__(self,x):
        self.num=x
class Girl:
    def __init__(self,x):
        self.num=x
class banji:
    def __init__(self,a,b):
        self.boy=Boy(a)
        self.girl=Girl(b)
    def prt(self):
        print("this banji have {0} boys and {1} girls.".format(self.boy.num,self.girl.num))

B=banji(3,4)
B.prt()
#this banji have 3 boys and 4 girls.

类、类对象和实例对象

在这里插入图片描述
类对象:创建一个类,其实也是一个对象也在内存开辟了一块空间,称为类对象,类对象只有一个。
在这里插入图片描述
实例对象:就是通过实例化类创建的对象,称为实例对象,实例对象可以有多个。

# 实例化对象 a、b、c都属于实例对象。
a = A()
b = A()
c = A()

类属性:类里面方法外面定义的变量称为类属性。类属性所属于类对象并且多个实例对象之间共享同一个类属性,说白了就是类属性所有的通过该类实例化的对象都能共享。

class A():
    a = 0  # 类属性

    def __init__(self, xx):
        # 使用类属性可以通过 (类名.类属性)调用。
        A.a = xx

实例属性:实例属性和具体的某个实例对象有关系,并且一个实例对象和另外一个实例对象是不共享属性的,说白了实例属性只能在自己的对象里面使用,其他的对象不能直接使用,因为self是谁调用,它的值就属于该对象。

class 类名():
    __init__(self):
        self.name = xx #实例属性

-类属性和实例属性区别
1.类属性:类外面,可以通过实例对象.类属性和类名.类属性进行调用。类里面,通过self.类属性和类名.类属性进行调用。
2.实例属性 :类外面,可以通过实例对象.实例属性调用。类里面,通过self.实例属性调用。
3.实例属性就相当于局部变量。出了这个类或者这个类的实例对象,就没有作用了。
4.类属性就相当于类里面的全局变量,可以和这个类的所有实例对象共享。

# 创建类对象
class Test(object):
    class_attr = 100  # 类属性

    def __init__(self):
        self.sl_attr = 100  # 实例属性

    def func(self):
        print('类对象.类属性的值:', Test.class_attr)  # 调用类属性
        print('self.类属性的值', self.class_attr)  # 相当于把类属性 变成实例属性
        print('self.实例属性的值', self.sl_attr)  # 调用实例属性


a = Test()
a.func()

# 类对象.类属性的值: 100
# self.类属性的值 100
# self.实例属性的值 100

b = Test()
b.func()

# 类对象.类属性的值: 100
# self.类属性的值 100
# self.实例属性的值 100

a.class_attr = 200
a.sl_attr = 200
a.func()

# 类对象.类属性的值: 100
# self.类属性的值 200
# self.实例属性的值 200

b.func()

# 类对象.类属性的值: 100
# self.类属性的值 100
# self.实例属性的值 100

Test.class_attr = 300
a.func()

# 类对象.类属性的值: 300
# self.类属性的值 200
# self.实例属性的值 200

b.func()
# 类对象.类属性的值: 300
# self.类属性的值 300
# self.实例属性的值 100
  • 属性与方法名相同,属性会覆盖方法。
class A:
    def a(self):
        print("hh")
b=A()
b.a()#hh
b.a=1
print(b.a)#1
b.a()
#TypeError: 'int' object is not callable

什么是绑定?

Python 严格要求方法需要有实例才能被调用,这种限制其实就是 Python 所谓的绑定概念。

Python 对象的数据属性通常存储在名为.__ dict__的字典中,我们可以直接访问__dict__,或利用 Python 的内置函数vars()获取.__ dict__。

class A:
    def set(self,a,b):
        self.a=a
        self.b=b
    def prt(self):
        print("a:",self.a,"b:",self.b)
hh=A()
print(hh.__dict__)
#{}
print(vars(hh))
#{}
print(A.__dict__)
#{'__module__': '__main__', 'set': <function A.set at 0x000001AAC8A83DC0>, 'prt': <function A.prt at 0x000001AAC8A83E50>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}

hh.set(1,2)
print(hh.__dict__)
#{'a': 1, 'b': 2}
print(vars(A))
#{'__module__': '__main__', 'set': <function A.set at 0x000001AAC8A83DC0>, 'prt': <function A.prt at 0x000001AAC8A83E50>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}

一些相关的内置函数(BIF)

1.issubclass(class, classinfo) 方法用于判断参数 class 是否是类型参数 classinfo 的子类。
2.一个类被认为是其自身的子类。
3.classinfo可以是类对象的元组,只要class是其中任何一个候选类的子类,则返回True。
例:

class A:
    pass
class B(A):
    pass


print(issubclass(B, A))  # True
print(issubclass(B, B))  # True
print(issubclass(A, B))  # False
print(issubclass(B, object))  # True

4.isinstance(object, classinfo) 方法用于判断一个对象是否是一个已知的类型,类似type()。
5.type()不会认为子类是一种父类类型,不考虑继承关系。
6.isinstance()会认为子类是一种父类类型,考虑继承关系。
7.如果第一个参数不是对象,则永远返回False。
8.如果第二个参数不是类或者由类对象组成的元组,会抛出一个TypeError异常。

a = 2
print(isinstance(a, int))  # True
print(isinstance(a, str))  # False
print(isinstance(a, (str, int, list)))  # True

class A:
    pass
class B(A):
    pass


print(isinstance(A(), A))  # True
print(type(A()) == A)  # True
print(isinstance(B(), A))  # True
print(type(B()) == A)  # False

9.hasattr(object, name)用于判断对象是否包含对应的属性。

class Coordinate:
    x = 10
    y = -5
    z = 0


point1 = Coordinate()
print(hasattr(point1, 'x'))  # True
print(hasattr(point1, 'y'))  # True
print(hasattr(point1, 'z'))  # True
print(hasattr(point1, 'no'))  # False

10.getattr(object, name[, default])用于返回一个对象属性值

class A(object):
    bar = 1


a = A()
print(getattr(a, 'bar'))  # 1
print(getattr(a, 'bar2', 3))  # 3
print(getattr(a, 'bar2'))
# AttributeError: 'A' object has no attribute 'bar2'
class A(object):
    def set(self, a, b):
        x = a
        a = b
        b = x
        print(a, b)


a = A()
c = getattr(a, 'set')
c(a='1', b='2')  # 2 1

11.setattr(object, name, value)对应函数 getattr(),用于设置属性值,该属性不一定是存在的。

class A(object):
    bar = 1


a = A()
print(getattr(a, 'bar'))  # 1
setattr(a, 'bar', 5)
print(a.bar)  # 5
setattr(a, "age", 28)
print(a.age)  # 28

12.delattr(object, name)用于删除属性。

class Coordinate:
    x = 10
    y = -5
    z = 0


point1 = Coordinate()

print('x = ', point1.x)  # x =  10
print('y = ', point1.y)  # y =  -5
print('z = ', point1.z)  # z =  0

delattr(Coordinate, 'z')

print('--删除 z 属性后--')  # --删除 z 属性后--
print('x = ', point1.x)  # x =  10
print('y = ', point1.y)  # y =  -5

# 触发错误
print('z = ', point1.z)
# AttributeError: 'Coordinate' object has no attribute 'z'

13.class property([fget[, fset[, fdel[, doc]]]])用于在新式类中返回属性值。
fget – 获取属性值的函数
fset – 设置属性值的函数
fdel – 删除属性值函数
doc – 属性描述信息

class C(object):
    def __init__(self):
        self.__x = None

    def getx(self):
        return self.__x

    def setx(self, value):
        self.__x = value

    def delx(self):
        del self.__x

    x = property(getx, setx, delx, "I'm the 'x' property.")


cc = C()
cc.x = 2
print(cc.x)  # 2

del cc.x
print(cc.x)
# AttributeError: 'C' object has no attribute '_C__x'
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

colaj_49485675

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值