美文网首页
面向对象编程基础-Python类(二)

面向对象编程基础-Python类(二)

作者: Dozing | 来源:发表于2019-07-11 23:59 被阅读0次

1

对象既包含数据(变量,更习惯称之为特性,attribute),也包含代码(函数,也称为方法)。它是某一类具体事物的特殊实例

2

>>>class Person():
           def __init__(self):
           pass

__init__self就是实际Python类的定义形式.__init__()是Python中一个特殊的函数名,用于根据类的定义创建实例对象。self参数指向了这个正在被创建的对象本身

3

>>>class Person():
           def __init__(self,name):
                     self.name = name
>>>

现在,用Person类创建一个对象,为name特性传递一个字符串参数:

hunter = Person('Elmer Fudd')

上面这短短的一行代码实际做了以下工作:

  • 查看Person类的定义
  • 在内存中实例化(创建)一个新的对象
  • 调用对象的__init__方法,将这个新创建的对象作为self传入,并将另一个参数('Elmer Fudd')作为name传入
  • name的值存入对象
  • 返回这个新的对象
  • 将名字hunter与这个对象关联

这个新对象与任何其他的对象一样,你可以把它当作列表,元组,字典或集合中的元素。也可以把它当作参数传递给函数,或者把它做为函数的返回结果。

刚刚传入的name参数此时又在哪儿呢?它作为对象的特性存储在了对象里,可以直接对它进行读写操作:

>>>print('The mighty hunter:',hunter.name)
The mighty hunter:Elmer Fudd

4

>>>class Car():
             def exclaim(self):
                   print('I'm a car!')
>>>car = Car()
>>>car.exclaim()
I'm a car!

上面的语句,Python在背后做了一下两件事情:

  • 查找car对象所属的类(Car):
  • car对象作为self参数传给Car类所包含的exclaim()方法
    了解了调用机制后,甚至可以像下面这样进行调用,这与普通的调用语法(car.exclaim())效果完全一致。
>>>Car.exclaim(car)
I'm a Car!

当然,我们没有理由使用这种臃肿的语法

5

在类的定义中,以self作为第一个参数的方法都是实例方法(instance method)

6 (Python编程入门到实践)例子

class Dog():
         def __init__(self,name,age):
         """初始化属性name和age"""
                   self.name = name
                   self.age = age

        def sit(self):
            print(self.name.title() + "it now sitting.")

        def roll_over(self):
            print(self.name.title() + "rolled over!")        
  • 类中的函数称为方法
  • Python调用这个__init__()方法来创建Dog实例时,将自动传入实参self。每个与类相关联的方法调用都自动传递实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法
  • 两个变量都有前缀self。以 self为前缀的变量都可供类中所有方法使用,我们还可以通过类中的任何实例来访问这些变量。self.name=name获取存储在形参name中的值,并将其存储到变量name中,然后该变量被关联到当前创建的实例。像这样可通过实例访问的变量称为属性

7

Python 使用self参数来找到正确的对象所包含的特性和方法

>>> class Person():
...     def __init__(self,name):
...             self.name = name
...     def age():
...             print('Age = 15')
...
>>> A = Person('Tom')
>>> A.name
'Tom'
>>> A.age()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: age() takes 0 positional arguments but 1 was given
>>> Person.name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Person' has no attribute 'name'
>>> Person.age()
Age = 15
>>> class Person():
...     Age = 15
...     def name(self):
...             self.Name = 'Tom'
...
>>> A = Person()
>>> A.Age
15
>>> A.name()
>>> A.Name
'Tom'
>>> Person.Age
15
>>> Person.name()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: name() missing 1 required positional argument: 'self'
>>>

实例对象可以访问类的属性(特性),但不能访问类的方法

>>> class Dog():
...     def __init__(self):
...             self.name = 'Dan'
...             self.age = 8
...
>>> A = Dog()
>>> A.name
'Dan'
>>> A.age
8
>>> class woft():
...     self.name = 'tom'
...     self.age = 15
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in woft
NameError: name 'self' is not defined
>>>

实例的初始化必须用到__init__方法

>>> class Dog():
...     color = 'Black'
...     def __init__(self):
...             self.name = 'Dan'
...             self.age = 15
...
>>> A = Dog()
>>> A.Size='Big'
>>> Dog.Sound='wow'
>>> A.name
'Dan'
>>> A.age
15
>>> A.Size
'Big'
>>> A.Sound
'wow'
>>> A.color
'Black'
>>> Dog.color
'Black'
>>> Dog.name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Dog' has no attribute 'name'
>>> Dog.Sound
'wow'
>>> Dog.age
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Dog' has no attribute 'age'
>>> Dog.Size
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Dog' has no attribute 'Size'
>>>

相关文章

  • Python面向对象(基础)

    面向对象 Python是支持面向对象的,面向对象编程是一种程序设计思想。 类和实例(基础) 面向对象最重要的就是类...

  • python面向对象学习笔记-01

    学习笔记 # 0,OOP-Python面向对象 - Python的面向对象 - 面向对象编程 - 基础 -...

  • python 面向对象的编程(一)

    python 同时支持面向对象编程和函数式编程的语言python面向对象的主题围绕 类 和 类实例 两个主题。面向...

  • Python全栈之路系列之面向对象基础

    面向对象基本介绍 Python编程方式: 面向过程编程 面向函数编程 面向对象编程 名称定义: 如果函数没有在类中...

  • python基础知识(四)---面向对面编程

    python 面向对面编程 面向对象编程(或者可以称为 面向类编程)。 面向对象 提供的是一种 "语法功能", ...

  • Python OOP-1

    0. OOP-Python面向对象 Python面向对象 面向对象编程基础公有私有继承组合,Mixin 魔法函数魔...

  • 面向对象编程基础-Python类(二)

    1 对象既包含数据(变量,更习惯称之为特性,attribute),也包含代码(函数,也称为方法)。它是某一类具体事...

  • python 面向对象编程

    面向对象编程 万物皆是对象,Python当然支持面向对象编程。类和对象是面向对象编程的两个主要方面,类创建一个新的...

  • python的面向对象

    python的面向对象(ObjectOriented,OO)-面向对象编程-基础-公有私有-继承-组合,Minxi...

  • 深入理解python之类的创建过程

    类是面向对象编程理论的基础,python作为一门支持面向对象的语言,其在类的创建机制上,与传统的编译型静态语言有着...

网友评论

      本文标题:面向对象编程基础-Python类(二)

      本文链接:https://www.haomeiwen.com/subject/huzjkctx.html