《Python 3 面向对象编程》学习笔记(二)-类属性(self变量)

《Python 3 面向对象编程》学习笔记(二)
类添加属性,类初始化对象,对象属性初始化

3. 类添加属性

在test.py中定义一个空类:

class Point:
	pass

并按‘F5’ Run an Debug,会自动打开python Shell,然后在python Shell中输入:

Point().x=10
Point().y=20
print(Point().x,Point().y)
Traceback (most recent call last):
File “<pyshell#2>”, line 1, in
print(Point().x,Point().y)
AttributeError: ‘Point’ object has no attribute ‘x’

发现: Point().x=10可以被解释,但print中出错:这时提示对象‘Point’,修改代码:

p1=Point()
p1.x=10
p1.y=20
print(p1.x,p1.y)
10 20

说明:类使用前必须‘实例化’,另发现:不需要改动类的定义,我们可以通过点标记法(dot notation)为实例对象设定任意属性。

import math
class Point:
  def move(self, x, y):
    self.x = x
    self.y = y
  def reset(self):
    self.move(0, 0)
  def calculate_distance(self, other_point):
    return math.sqrt(
    (self.x - other_point.x)**2 +
    (self.y - other_point.y)**2)

point1 = Point()
point2 = Point()
point1.reset()
point2.move(5,0)
print(point2.calculate_distance(point1))
assert (point2.calculate_distance(point1) ==
point1.calculate_distance(point2))
point1.move(3,4)
print(point1.calculate_distance(point2))
print(point1.calculate_distance(point1))

运行结果:
5.0
5.0
4.47213595499958
4.47213595499958

如果不明确设定Point 对象的位置属性x 和y,直接用move 方法或直接获取它们,我们将会得到一个没有真实位置的错误点.这句话有点费解,但是强调在对象的初始化(包括:对象属性)
示例:


>>> class Point:
	pass

>>> p.x=5
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    p.x=5
NameError: name 'p' is not defined
>>> p=Point()
>>> print(p.x)
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    print(p.x)
AttributeError: 'Point' object has no attribute 'x'
>>> p.x=5
>>> print(p.x)
5
>>> 

4. 对象初始化及属性的初始值

C++有构造函数(constructor)的概念,是创建对象时进行创建和初始化的特定方法。Python 有一点不一样,它同时拥有构造函数和初始化方法.。除非你需
要做一些异乎寻常的事,否则很少用到构造函数,所以我们就先讨论初始化方法。
Python 初始化方法和其他的方法一样,除了它有特定的名字__init__。开头和结尾的双下画线意味着这是一个特殊方法.
对象初始化

对象初始化及属性缺省值

对象初始化对应参数要匹配(可不可像C++ 一样重载同名函数)
属性可以设置初始值:我们将初始化语句放在__init__函数中

class Point:
	def __init__(self, x=0, y=0):
		self.move(x, y)

构造函数

与__init__相对应,构造函数名为__new__,并且只接收一个参数,即将要构造的类(它在构造对象之前调用,因此还没有self 参数)同时它必须返回新创建的对象.
所以:point=Point() 应该是先用__new__构造了对象并返回对象,然后调用了__init__

[1] Phillips D. Python 3面向对象编程[M]. 电子工业出版社, 2018.

  • 11
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值